<template>
  <div>
    <MOSTY.PageTree :pageTitle="'字典列表'" :isShowLeftTree="false">
      <template #serach>
        <el-divider />
        <MOSTY.Search :searchArr="searchArr" isEnterSubmit @submit="handleFilter" />
        <el-divider />
        <div class="btnBox">
          <el-button type="primary" @click="addDict">
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>新增</span>
          </el-button>
        </div>
      </template>
      <template #table>
        <div class="eltab9">
          <el-table :data="tableData" border row-key="id" stripe
            :tree-props="{ children: 'itemList', hasChildren: true }" style="width: 100%" height="100%" :key="keyCount">
            <!-- <el-table-column label="#" type="index" /> -->
            <!-- <el-table-column prop="id" label="id"> </el-table-column> -->
            <el-table-column sortable prop="zdbh" label="字典编号" show-overflow-tooltip>
            </el-table-column>
            <el-table-column sortable prop="zdmc" label="字典名称" show-overflow-tooltip>
            </el-table-column>
            <el-table-column sortable label="状态" width="80px">
              <template #default="{ row }">
                <div>
                  <el-tag size="small" type="success" v-if="row.xtZxbz == 0">正常</el-tag>
                  <el-tag size="small" type="danger" v-else-if="row.xtZxbz == 1">注销</el-tag>
                  <el-tag size="small" type="info" v-else>未知</el-tag>
                </div>
              </template>
            </el-table-column>
            <el-table-column sortable prop="bz" label="备注" show-overflow-tooltip>
            </el-table-column>
            <el-table-column sortable prop="xtZhxgsj" label="更新时间">
              <template #default="{ row }">
                {{ $filters.dateFilter(row.xtZhxgsj) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" fixed="right" width="260">
              <template #default="{ row }">
                <el-button @click="updateDict(row)" size="small"> 修改</el-button>
                <el-button @click="toGoPage(row)" size="small">
                  {{ row.zdlx === 1 ? "列表" : "树形" }}</el-button>
                <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要注销?"
                  @confirm="delDict(row)" @cancel="cancelEvent">
                  <template #reference>
                    <el-button type="danger" size="small">注销</el-button>
                  </template>
                </el-popconfirm>
              </template>
            </el-table-column>
          </el-table>
          <div class="fenye">
            <el-pagination size class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
              :current-page="listQuery.current" :page-sizes="[2, 5, 10, 20]" :page-size="listQuery.size"
              layout="total, prev, pager, next, sizes, jumper" :total="total">
            </el-pagination>
          </div>
        </div>
      </template>
    </MOSTY.PageTree>
    <el-dialog custom-class="way" v-model="dialogFormVisible" :before-close="closeDialog" :title="isEdit ? '修改' : '新增'">
      <el-form class="mosty-from-wrap" :inline="true" label-position="top" :model="dialogForm" :rules="rules"
        ref="elform">
        <el-form-item prop="zdmc" class="one" label="字典名称" style="width: 100%">
          <el-input style="width: 100%" v-model="dialogForm.zdmc" show-word-limit maxlength="50"
            autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item class="one" prop="zdbh" label="字典编码" style="width: 100%">
          <el-input style="width: 100%" v-model="dialogForm.zdbh" show-word-limit maxlength="30"
            autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item prop="yybz" class="one" label="引用标准" style="width: 100%">
          <el-input style="width: 100%" v-model="dialogForm.yybz" show-word-limit maxlength="50"
            autocomplete="off"></el-input>
        </el-form-item>
        <el-form-item class="one" prop="xtZxbz" label="状态" style="width: 100%">
          <el-select style="width: 100%" v-model="dialogForm.xtZxbz">
            <el-option label="正常" :value="0"></el-option>
            <el-option label="注销" :value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="one" label="是否是树形结构" prop="zdlx" style="width: 100%">
          <el-select style="width: 100%" v-model="dialogForm.zdlx" placeholder="请选择">
            <el-option label="列表" :value="1"></el-option>
            <el-option label="树形" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item class="one" label="备注" style="width: 100%">
          <el-input style="width: 100%" v-model="dialogForm.bz" :autosize="{ minRows: 2, maxRows: 4 }" show-word-limit
            maxlength="200" type="textarea"></el-input>
        </el-form-item>
      </el-form>
      <div class="head_box tr mt20 pr30">
        <!-- 修改 -->
        <el-button v-if="isEdit" type="primary" size="small" @click="onSave" :loading="buttonLoading"><el-icon>
            <DocumentChecked />
          </el-icon>
          <span>保存</span></el-button>
        <!-- 新增 -->
        <el-button v-else type="primary" size="small" @click="onAdd" :loading="buttonLoading"><el-icon>
            <DocumentChecked />
          </el-icon>
          <span>保存</span></el-button>
        <el-button size="small" @click="closeDialog"> <el-icon>
            <DocumentDelete />
          </el-icon>
          <span>关闭</span></el-button>
      </div>
    </el-dialog>
    <div v-if="dialogChildren" class="dialog">
      <component :is="defineAsyncComponent(() => import('@/views/systemConfig/dict/detail'))" :params="dictDetailParams"
        @cancel="dialogChildren = false"></component>
    </div>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import * as MOSTY from "@/components/MyComponents/index";
import { ref, reactive, onMounted, getCurrentInstance, onUnmounted, defineAsyncComponent } from "vue";
import {
  getAllSysDict,
  updateSysDict,
  addSysDict,
  deleteSysDict
} from "@/api/sysDict";
import { useRouter } from "vue-router";
const { proxy } = getCurrentInstance();
const keyCount = ref(0); //tabel组件刷新值
const elform = ref(null);
const dialogChildren = ref(false)
const searchArr = reactive([
  {
    showType: "input",
    label: '字典名称:',
    prop: "dictName",
    width: '250px',
    placeholder: '请输入字典名称'
  },
  {
    showType: "input",
    label: '字典编码:',
    prop: "dictCode",
    width: '250px',
    placeholder: '请输入字典编码'
  },
  {
    showType: "select",
    label: '字典状态:',
    prop: "xtZxbz",
    width: '250px',
    placeholder: '请选择状态',
    options: [{ label: '正常', value: '0' }, { label: '注销', value: '1' }],
  },
]);
const total = ref(0);
const buttonLoading = ref(false);
const listQuery = ref({
  current: 1,
  size: 20,
  dictName: "",
  dictCode: "",
  xtZxbz: ""
});
const reset = () => {
  listQuery.value = {
    current: 1,
    size: 20,
    dictName: "",
    dictCode: "",
    xtZxbz: ""
  };
  getListData();
};
const dictDetailParams = ref();//字典选中的详情参数
const isEdit = ref(true);
const dialogForm = ref({});
// 数据相关
const tableData = ref([]);
const dialogFormVisible = ref(false);
// 获取数据的方法
const getListData = async () => {
  const params = listQuery.value;
  const res = await getAllSysDict(params);
  tableData.value = res?.records;
  total.value = Number(res.total);
};
//验证
const rules = ref({
  zdmc: [{ required: true, message: "请输入字典名称", trigger: "change" }],
  zdbh: [{ required: true, message: "请输入字典编码", trigger: "change" }],
  xtZxbz: [{ required: true, message: "请选择业务类别", trigger: "change" }],
  zdlx: [{ required: true, message: "请选择字典类型", trigger: "change" }],
  yybz: [{ required: true, message: "请填写引用标准", trigger: "change" }]
});

const handleFilter = (obj) => {
  if (obj) {
    listQuery.value.dictName = obj.dictName ? obj.dictName : null
    listQuery.value.dictCode = obj.dictCode ? obj.dictCode : null
    listQuery.value.xtZxbz = obj.xtZxbz ? obj.xtZxbz : null
  }
  listQuery.value.current = 1;
  getListData();
};
getListData();

// 分页相关
/**
 * size 改变触发
 */
const handleSizeChange = (currentSize) => {
  listQuery.value.size = currentSize;
  getListData();
};

/**
 * 页码改变触发
 */
const handleCurrentChange = (currentPage) => {
  listQuery.value.current = currentPage;
  getListData();
};
const cancelEvent = () => { };

/**修改字典 */
const updateDict = (row) => {
  isEdit.value = true;
  dialogForm.value = { ...row };
  dialogForm.value.zdywlb = Number(dialogForm.value.zdywlb);

  dialogFormVisible.value = true;
};

const delDict = (row) => {
  deleteSysDict({
    id: Number(row.id)
  }).then((res) => {
    ElMessage.success("注销成功");
    handleFilter();
  });
};

const addDict = (row) => {
  isEdit.value = false;
  dialogForm.value = {};
  dialogFormVisible.value = true;
};
const isAvailable = (val) => {
  if (val === 0) return true;
  if (
    val == null ||
    val == undefined ||
    val == "" ||
    val == "undefined" ||
    val == "null"
  ) {
    return false;
  } else {
    return true;
  }
};
const onSave = () => {
  elform.value.validate((valid) => {
    if (!valid) {
      ElMessage.error("请完成必填项！");
      return false;
    }
    buttonLoading.value = true;
    updateSysDict({
      bz: dialogForm.value.bz,
      id: dialogForm.value.id,
      yybz: dialogForm.value.yybz,
      zdbh: dialogForm.value.zdbh,
      zdlx: dialogForm.value.zdlx,
      zdmc: dialogForm.value.zdmc,
      zdywlb: dialogForm.value.zdywlb,
      xtZxbz: dialogForm.value.xtZxbz
    })
      .then((res) => {
        dialogFormVisible.value = false;
        ElMessage.success("修改成功");
        buttonLoading.value = false;
        handleFilter();
      })
      .finally(() => {
        buttonLoading.value = false;
      });
  });
};

const onAdd = () => {
  elform.value.validate((valid) => {
    if (!valid) {
      ElMessage.error("请完成必填项！");
      return false;
    }
    buttonLoading.value = true;
    addSysDict({
      bz: dialogForm.value.bz,
      // id: dialogForm.value.id,
      yybz: dialogForm.value.yybz,
      zdbh: dialogForm.value.zdbh,
      zdlx: dialogForm.value.zdlx,
      zdmc: dialogForm.value.zdmc,
      zdywlb: dialogForm.value.zdywlb
    })
      .then((res) => {
        ElMessage.success("添加成功");
        dialogFormVisible.value = false;
        buttonLoading.value = false;
        handleFilter();
      })
      .finally(() => {
        buttonLoading.value = false;
      });
  });
};

const closeDialog = () => {
  proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
    .then(() => {
      dialogForm.value = {};
      dialogFormVisible.value = false;
    })
    .catch(() => {
      // catch error
    })

};

const toGoPage = (row) => {
  const { zdbh, zdlx } = row
  dictDetailParams.value = { zdbh, zdlx }
  dialogChildren.value = true
  // router.push({
  //   path: "/dict/detail",
  //   query: {
  //     zdbh: row.zdbh,
  //     zdlx: row.zdlx,
  //   }
  // });
};

onMounted(() => {

  proxy.mittBus.on("mittFn", (data) => {
    keyCount.value = data;
  });
});
onUnmounted(() => {
  proxy.mittBus.off("mittFn");
});
</script>

<style lang="scss" scoped>
@import "~@/assets/css/layout.scss";
@import "~@/assets/css/element-plus.scss";

.btnBox {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  margin-bottom: 12px;
}


::v-deep .el-dialog__body {
  padding: 20px 20px 20px 52px !important;
}
</style>
