<!-- eslint-disable vue/multi-word-component-names -->
<template>
  <div>
    <a-table
      :columns="tableColumns"
      :data-source="data"
      bordered
      :pagination="false"
      :scroll="{ y: 530 }">
      <template #bodyCell="{ text, column, record }">
        <template v-if="column.dataIndex === 'showed'">
          <a-switch
            :checked="text"
            :checked-value="0"
            :unCheckedValue="1"
            @change="(checked) => updateShowed(record, true)" />
        </template>
        <template v-if="column.title === '操作'">
          <a-button type="link" @click="updateDict(record)">编辑</a-button>
          <a-button type="link" @click="deleteDict(record)">删除</a-button>
        </template>
      </template>
      <template #title>
        <div
          style="display: flex; align-items: center; justify-content: space-between; width: 100%">
          <div style="display: flex; align-items: center; width: 85%">
            <div style="width: 10%">数据报表</div>
            <a-input
              v-model:value="queryParams.grp"
              placeholder="请输入字典组名"
              style="width: 15%" />
            <a-input
              v-model:value="queryParams.grpDesc"
              placeholder="请输入字典组名描述"
              style="width: 15%; margin-left: 10px" />
            <a-input
              v-model:value="queryParams.dicKey"
              placeholder="请输入字典Key"
              style="width: 15%; margin-left: 10px" />
            <a-input
              v-model:value="queryParams.cnValue"
              placeholder="请输入字典中文Value"
              style="width: 15%; margin-left: 10px" />
            <a-button type="primary" style="margin-left: 10px" @click="getTableList">
              查询
            </a-button>
          </div>
          <a-button type="primary" style="margin-left: 10px" @click="addDict"> 新增 </a-button>
        </div>
      </template>
    </a-table>

    <a-drawer
      :width="600"
      :visible="visible"
      :title="updateInfo && updateInfo.id ? '编辑' : '新增'"
      :body-style="{ paddingBottom: '80px' }"
      :footer-style="{ textAlign: 'right' }"
      destroyOnClose
      @close="onClose">
      <a-form
        ref="formRef"
        :model="updateInfo"
        :rules="rules"
        :label-col="labelCol"
        :wrapper-col="wrapperCol">
        <a-form-item ref="grp" label="字典组名" name="grp">
          <a-input v-model:value="updateInfo.grp" placeholder="请输入字典组名" />
        </a-form-item>
        <a-form-item ref="grpDesc" label="字典组名描述" name="grpDesc">
          <a-input v-model:value="updateInfo.grpDesc" placeholder="请输入字典组名描述" />
        </a-form-item>
        <a-form-item ref="dicKey" label="字典Key" name="dicKey">
          <a-input v-model:value="updateInfo.dicKey" placeholder="请输入字典Key" />
        </a-form-item>
        <a-form-item ref="cnValue" label="字典中文Value" name="cnValue">
          <a-input v-model:value="updateInfo.cnValue" placeholder="请输入字典中文Value" />
        </a-form-item>
        <a-form-item ref="enValue" label="字典英文Value" name="enValue">
          <a-input v-model:value="updateInfo.enValue" placeholder="请输入字典英文Value" />
        </a-form-item>
        <a-form-item ref="description" label="字典描述" name="description">
          <a-input v-model:value="updateInfo.description" placeholder="请输入字典描述" />
        </a-form-item>
        <a-form-item ref="parentId" label="父级ID" name="parentId">
          <a-input v-model:value="updateInfo.parentId" placeholder="请输入父级ID" />
        </a-form-item>
        <a-form-item ref="seq" label="排序数字" name="seq">
          <a-input v-model:value="updateInfo.seq" placeholder="请输入排序数字" />
        </a-form-item>
        <a-form-item ref="showed" label="是否展示" name="showed">
          <!-- <a-input v-model:value="updateInfo.showed" placeholder="请输入是否展示" /> -->
          <a-switch
            :checked="updateInfo.showed"
            :checked-value="0"
            :unCheckedValue="1"
            @change="updateShowed(updateInfo, false)" />
        </a-form-item>
        <!-- <a-form-item label="计量单位" name="unit">
          <a-cascader v-model:value="formState.unit" :options="measurementUnit" />
        </a-form-item>
        <a-form-item label="自动采集节点" name="collectionNode">
          <a-tree-select
            v-model:value="formState.collectionNode"
            :tree-line="true"
            :tree-data="treeData" />
        </a-form-item>
        <a-form-item label="计算碳排" name="isComputeCarbon">
          <a-radio-group v-model:value="formState.isComputeCarbon" @change="changeRadio">
            <a-radio :value="0">是</a-radio>
            <a-radio :value="1">否</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="排放类型" name="emissionType" :required="isRequired">
          <a-select v-model:value="formState.emissionType" placeholder="请选择排放类型">
            <a-select-option v-for="(item, index) in emissionTypeDic" :key="index" :value="item.id">
              {{ item.cnValue }}
            </a-select-option>
          </a-select>
        </a-form-item> -->
      </a-form>
      <template #footer>
        <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
        <a-button type="primary" @click="onSubmit">确定</a-button>
      </template>
    </a-drawer>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onMounted, defineOptions } from 'vue';
  import { http } from '/nerv-lib/util/http';
  import type { FormInstance, Rule } from 'ant-design-vue/es/form';
  import { tableColumns } from './config';
  import { dict } from '/@/api/dict';
  import { NsMessage } from '/nerv-lib/component';
  import { Modal } from 'ant-design-vue';
  defineOptions({
    energyType: 'dictIndex', // 与页面路由name一致缓存才可生效
  });

  const data = ref([]);
  const updateInfo = ref({});
  const formRef = ref<FormInstance | null>(null);

  const queryParams = ref({
    grp: '',
    grpDesc: '',
    dicKey: '',
    cnValue: '',
  });
  const orgId = ref('');
  const result = JSON.parse(sessionStorage.getItem('ORGID')!);
  orgId.value = result;
  const fetch = (api, params = { orgId }) => {
    return http.post(api, params);
  };

  // 获取表格数据
  const getTableList = () => {
    fetch(dict.dictionaryUnitManagement, queryParams.value).then((res) => {
      data.value = res.data;
    });
  };
  // 修改是否显示状态
  const updateShowed = (record: any, falg: Boolean) => {
    if (record.showed == 0) {
      record.showed = 1;
    } else {
      record.showed = 0;
    }
    if (falg) {
      fetch(dict.updateDictionary, record).then((res) => {
        getTableList();
      });
    } else {
    }
  };

  const visible = ref(false);
  // const formState = ref({
  //   orgId: orgId.value,
  // });
  const labelCol = { span: 5 };
  const wrapperCol = { span: 19 };
  // 定义form表单的必填
  const rules: Record<string, Rule[]> = {
    grp: [{ required: true, message: '请输入字典组名', trigger: 'change' }],
    grpDesc: [{ required: true, message: '请输入字典组名描述', trigger: 'change' }],
    dicKey: [{ required: true, message: '请输入字典Key', trigger: 'change' }],
    cnValue: [{ required: true, message: '请输入字典中文Value', trigger: 'change' }],
    seq: [{ required: true, message: '请输入排序数字', trigger: 'change' }],
    showed: [{ required: true, message: '请输入是否展示', trigger: 'change' }],
  };
  // interface FormState {
  //   energyType: string;
  //   unit: string;
  //   collectionNode: string;
  //   emissionType: string | undefined;
  //   isComputeCarbon: string;
  //   janFlag: string;
  //   febFlag: string;
  //   marFlag: string;
  //   aprFlag: string;
  //   mayFlag: string;
  //   junFlag: string;
  //   julFlag: string;
  //   augFlag: string;
  //   sepFlag: string;
  //   octFlag: string;
  //   novFlag: string;
  //   decFlag: string;
  // }
  // 关闭新增抽屉
  const onClose = () => {
    visible.value = false;
    // formState.value = {
    //   orgId: orgId.value,
    // };
    // formRef.value.resetFields();
  };
  // 打开编辑页
  const updateDict = (record: any) => {
    updateInfo.value = record;
    visible.value = true;
    // todo 打开编辑页
  };
  // 打开新增页
  const addDict = () => {
    updateInfo.value = {};
    updateInfo.value.showed = 1;
    visible.value = true;
    // todo 打开编辑页
  };

  // 点击确定提交
  const onSubmit = () => {
    debugger;
    formRef.value
      ?.validate()
      .then((valid) => {
        if (valid) {
          if (updateInfo.value.id) {
            fetch(dict.updateDictionary, updateInfo.value).then((res) => {
              if (res.retcode == 0) {
                visible.value = false;
                NsMessage.success('保存成功');
                getTableList();
              }
            });
          } else {
            fetch(dict.createDictionary, updateInfo.value).then((res) => {
              if (res.retcode == 0) {
                visible.value = false;
                NsMessage.success('保存成功');
                getTableList();
              }
            });
          }
        } else {
          console.log('表单验证失败');
        }
      })
      .catch((error) => {
        console.log('表单验证失败', error);
      });
  };

  // 删除字典
  const deleteDict = (record: any) => {
    Modal.confirm({
      title: '警告',
      // icon: createVNode(ExclamationCircleOutlined),
      content: '确定要删除么？',
      okText: '确认',
      okType: 'primary',
      cancelText: '取消',
      onOk() {
        // let params = ;
        // // http.post(dict.delDictionary, params).then((res) => {
        // //   if (res.retcode == 0) {
        // //     visible.value = false;
        // //     NsMessage.success('删除成功');
        // //     getTableList();
        // //   }
        // // });
        fetch(dict.delDictionary, { id: record.id }).then((res) => {
          if (res.retcode == 0) {
            visible.value = false;
            NsMessage.success('删除成功');
            getTableList();
          }
        });
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  };
  onMounted(() => {
    getTableList();
  });
</script>
<style scoped lang="less">
  ::v-deep .ant-table-title {
    display: flex;
  }
  ::v-deep .ant-table-container {
    padding: 0px 16px;
  }
</style>
<style scoped>
  th.column-money,
  td.column-money {
    text-align: right !important;
  }
</style>
