<template>
  <div class="system-dic-dialog-container">
    <el-dialog
        :title="state.dialog.title"
        v-model="state.dialog.isShowDialog"
        width="869px"
        draggable
        destroy-on-close
        :close-on-click-modal="false"
    @close="closeDialog">
      <el-alert v-if="state.ruleForm.id>0" title="字典修改影响全局数据，请谨慎修改" type="error" :closable="false" class="mb20"></el-alert>
      <el-form ref="formRef" :model="state.ruleForm" size="default" label-width="90px">
        <el-row :gutter="35">
          <el-col :xs="24" :sm="12" :md="12" :lg="12" :xl="12" class="mb20">
            <el-form-item label="字典类型">
              <el-input v-model="state.ruleForm.type" placeholder="请输入字典名称" :disabled="state.ruleForm.id>0"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
            <el-form-item label="字典描述">
              <el-input v-model="state.ruleForm.des" type="textarea" placeholder="请输入字典描述" @change="handleSetupDIctDes"
                        maxlength="150" show-word-limit></el-input>
            </el-form-item>
          </el-col>

          <!--					<el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                      <el-form-item label="字典状态">
                        <el-switch v-model="state.ruleForm.status" inline-prompt active-text="启" inactive-text="禁"></el-switch>
                      </el-form-item>
                    </el-col>-->

        </el-row>
      </el-form>
      <el-card shadow="hover">
        <el-button :top="-21" :left="-21" icon="Plus" title="新增" placement="leftTop" @click="onAddRow" v-auth="'dict.add'"></el-button>
<!--        <div v-waves class="triangle-left-btn" @click="onAddRow" v-auth="'dict.add'" title="新增" >
          <el-icon style="margin-top: -45px;margin-left:5px;color: #fff;font-weight: bold;font-size: 18px;">

            <ele-Plus/>
          </el-icon>
        </div>-->
        <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">

          <el-row :gutter="35" v-for="(v, k) in state.ruleForm.list" :key="k">
            <el-col :xs="24" :sm="5" :md="5" :lg="5" :xl="5" class="mb20">
              <el-form-item :prop="`list[${k}].label`" class="dict-head">
                <template #label>

                  <el-button type="danger" circle size="small" @click="onDelRow(k)" >
                    <SvgIcon name="ele-Delete"></SvgIcon>
                  </el-button>
                  <span class="ml10" :style="{'color':v.color}">名称</span>
                </template>
                <el-input v-model="v.label" style="width: 100%" placeholder="请输入字典名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="5" :md="5" :lg="5" :xl="5" class="mb20">
              <el-form-item label="码值" :prop="`list[${k}].value`">
                <el-input-number
                    v-model="v.value"
                    controls-position="right"
                    :min="1"
                    :max="100"
                    placeholder="请输入字典码值"
                ></el-input-number>
                <!--                <el-input type="number" v-model="v.value" style="width: 100%" ></el-input>-->
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="5" :md="5" :lg="5" :xl="5" class="mb20">
              <el-form-item label="排序" :prop="`list[${k}].value`">
                <el-input-number
                    v-model="v.weight"
                    controls-position="right"
                    :min="1"
                    :max="100"
                    placeholder="请输入排序权重"
                ></el-input-number>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="5" :md="5" :lg="5" :xl="5" class="mb20">
              <el-form-item label="颜色" :prop="`list[${k}].value`">
                <ExtColor v-model="v.color"></ExtColor>
              </el-form-item>
            </el-col>

            <el-col :xs="24" :sm="4" :md="4" :lg="4" :xl="4" class="mb20">
              <el-form-item label="图标" :prop="`list[${k}].icon`">
                <ExtIcon v-model="v.icon" />
<!--                <IconSelector @get="onGetIcon" @clear="onClearIcon" v-model="v.icon" />-->
              </el-form-item>
            </el-col>
          </el-row>
        </el-col>
      </el-card>
      <template #footer>
				<span class="dialog-footer">
					<el-button @click="onCancel" size="default">取 消</el-button>
					<el-button type="primary" @click="onSubmit" :loading="state.btnLoading"
                     size="default">{{ state.dialog.submitTxt }}</el-button>
				</span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts" name="DictDialog">
import {reactive, ref,toRaw,defineAsyncComponent} from 'vue';
import {Msg} from "/@/utils/message";
import {$body, $get} from "/@/utils/request";
import u from '/@/utils/u'
import ExtColor from "/@/components/form/ExtColor.vue";
import {verifySpecialChar} from "/@/utils/toolsValidate";
const ExtIcon = defineAsyncComponent(() => import('/@/components/form/ExtIcon.vue'));


// 定义子组件向父组件传值/事件
const emit = defineEmits(['refresh']);
const formRef = ref();

// 定义变量内容
const dicDialogFormRef = ref();

const initState =()=>( {
  ruleForm: {
    dicName: '', // 字典名称
    fieldName: '', // 字段名
    status: true, // 字典状态
    list: [] as Array<any>, // 子集字段 + 属性值
    des: '', // 字典描述
    type: '',
    id: 0,
  },
  dialog: {
    isShowDialog: false,
    type: '',
    title: '',
    submitTxt: '',
  },
  btnLoading: false,
})

const state = reactive(initState());

const _form = toRaw(state)

// 打开弹窗
const open = (action: string = 'add', row: any) => {
  state.dialog.title = u.dialog.actions[action].title + "字典"
  state.dialog.submitTxt = u.dialog.actions[action].btn + "字典"
  state.dialog.isShowDialog = true;
  if (action !== 'add') {
    loadData(row.type);
    state.ruleForm.type = row.type;
    state.ruleForm.des = row.des;
  }
};
// 关闭弹窗
const closeDialog = () => {
  state.dialog.isShowDialog = false;
  console.log(JSON.stringify(_form))
  Object.assign(state,initState())
};
// 取消
const onCancel = () => {
  closeDialog();
};
// 提交
const onSubmit = () => {
  console.log(JSON.stringify(state.ruleForm.list))
  if (u.isEmptyOrNull(state.ruleForm.list)) {
    Msg.message('字典内容不能为空', 'error');
    return;
  }

  let checked = true;
  state.ruleForm.list.forEach((item: any) => {
    if (u.isEmptyOrNull(item.label)) {
      Msg.message('字典内容不能为空', 'error');
      checked = false;
      return;
    }
    if (verifySpecialChar(item.label)) {
      Msg.message('字典内容不能包含特殊字符', 'error');
      checked = false;
      return;
    }
    if (!item.value || item.value <= 0) {
      Msg.message('字典码值不能为空', 'error');
      checked = false;
      return;
    }
  })
  if (!checked) return;
  const url = state.ruleForm.id > 0 ? "dict/modify" : "dict/add"
  $body(url, state.ruleForm.list).then(() => {
    state.btnLoading = false;
    Msg.message('操作成功');
    console.log('submit!')
    closeDialog();
    emit('refresh');
  }).catch(() => {
    state.btnLoading = false;
    Msg.message('操作失败', 'error');
  })


  /*  formRef.value.validate((valid,fields)=>{
      state.btnLoading = true;

    }).catch(e => {
      state.btnLoading = false;
      Msg.message('请完整填写表单', 'error');
    })*/
};

const handleFormChange = (formData: any) => {
  console.log(formData)
}

// 初始化表格数据
const loadData = (type: string) => {
  $get(`dict/detail/${type}`).then((res: any) => {
    state.ruleForm.list = res[type];
    if (!u.isEmptyOrNull(res)) {
      state.ruleForm.id = res[type][0].id;
    }
  })

}

const onAddRow = () => {
  state.ruleForm.list.unshift({
    type: state.ruleForm.type,
    des: state.ruleForm.des
  });
}

// 删除行
const onDelRow = (k: number) => {
  state.ruleForm.list.splice(k, 1);
};

const handleSetupDIctDes = (val:string)=>{
  if (!u.isEmptyOrNull(state.ruleForm.list)) {
    state.ruleForm.list.forEach(i=>i.des = val)
  }
}

// 获取当前点击的 icon 图标
const onGetIcon = (icon: string) => {
  console.log(icon);
};
// 清空当前点击的 icon 图标
const onClearIcon = (icon: string) => {
  console.log(icon);
};

// 暴露变量
defineExpose({
  open,
});
</script>

<style lang="scss" scoped>
.dict-head {
  :deep(.el-button) {
    margin-top: 5px;
  }
}

.recharge {
  flex: 1;
  padding: 20px;
  text-align: center;
  color: #fff;
  border-top-right-radius: 100px;
  border-bottom-right-radius: 100px;
  /* 关键在这里，设置切线的角度和长度 */
  background: linear-gradient(127deg, transparent 50px, rgb(247, 75, 33) 0);
  /* 设置之后需要把位置向相反的方向偏移，达到粘合 */
  margin-left: -50px;
}

</style>
