<template>
  <div class="__normal-page">
    <div class="__normal-tree" v-loading="loadingTree">
      <div class="tree-filter">
        <CusFormColumn
            :span="24"
            v-model:param="treeFilter">
          <template #suffix>
            <SvgIcon name="search"/>
          </template>
        </CusFormColumn>
      </div>
      <div class="tree-content">
        <template v-for="p in dictTree">
          <div class="tree-parent __hover" :class="{active: p.expend}" @click="p.expend = !p.expend">{{p.name}}</div>
          <template v-if="p.expend">
            <template v-for="s in p.children?.filter(v => v.name.includes(treeFilter))">
              <div class="tree-son __hover" :class="{active: selectDict === s.value}" @click="handleTreeClick(s.value)">{{s.name}}</div>
            </template>
          </template>
        </template>
      </div>
    </div>
    <div class="__normal-content" v-if="selectDict">
      <CusContent
          v-model:tableHead="tableHead"
          @handleReset="handleReset"
          @handleSearch="onSearch"
      >
        <template #fieldOut>
          <CusForm labelWidth="120px" @handleEnter="onSearch">
            <CusFormColumn
                :span="8"
                label="字典显示名称:"
                v-model:param="queryForm.dictLabel"/>
            <CusFormColumn
                :span="8"
                label="字典值内容:"
                v-model:param="queryForm.dictValue"/>
            <CusSearchButtons
                @handleReset="handleReset"
                @handleSearch="onSearch"
            />
          </CusForm>
        </template>
        <template #buttons>
          <div class="__cus-button_submit __hover" @click="onAdd">
            <SvgIcon name="add" size="16"/>新增
          </div>
        </template>
        <template #table>
          <CusTable
              v-loading="loading"
              ref="ref_cusTable"
              :tableData="queryResult.tableData"
              :tableHead="tableHead"
              :total="queryResult.total"
              :page="queryPage.pageNum"
              :pageSize="queryPage.pageSize"
              @handlePage="handlePage"
          >
            <template #updateTime-column-value="{ scope }">
              {{$util.YMDHms(scope.row.updateTime)}}
            </template>
            <template #do-column-value="{ scope }">
              <div class="__cus-table_do">
                <div class="__cus-table_do-green __hover" @click="onView(scope.row)">
                  <SvgIcon name="view" size="16"/>查看
                </div>
                <div class="__cus-table_do-blue __hover" @click="onEdit(scope.row)">
                  <SvgIcon name="edit" size="16"/>编辑
                </div>
                <div class="__cus-table_do-red __hover" @click="onDel(scope.row)">
                  <SvgIcon name="del" size="16"/>删除
                </div>
              </div>
            </template>
          </CusTable>
        </template>
      </CusContent>
    </div>
    <DetailCom v-model:show="showDetail" :transfer="transfer" @refresh="handleSearch()"/>
  </div>
</template>

<script lang="ts">
import {
  defineComponent,
  computed,
  onMounted,
  ref,
  reactive,
  watch,
  getCurrentInstance,
  ComponentInternalInstance,
  toRefs,
  nextTick
} from 'vue'
import {useStore} from 'vuex'
import {useRouter, useRoute} from 'vue-router'
import DetailCom from './detail.vue'
import { ElMessage, ElMessageBox } from 'element-plus';

export default defineComponent({
  name: '',
  components: {
    DetailCom
  },
  setup(props, {emit}) {
    const store = useStore();
    const router = useRouter();
    const route = useRoute();
    const that = (getCurrentInstance() as ComponentInternalInstance).appContext.config.globalProperties
    const state = reactive({
      //  加载中
      loading: false,
      //  查询分页参数
      queryPage: {
        pageNum: 1,
        pageSize: 10
      },
      //  查询结果
      queryResult: {
        total: 0,
        tableData: []
      },
      //  查询表单参数
      queryForm: <any>{},
      //  查询表单参数备份
      back_queryForm: {},
      //  表格表头
      tableHead: [
        {value: "dictLabel", label: "字典显示名称", show: true},
        {value: "dictValue", label: "字典值内容", show: true},
        {value: "dictSort", label: "排序", show: true},
        {value: "updateTime", label: "更新时间", show: true, width: 180},
        {value: "do", label: "操作", show: true, popover: true, width: 260},
      ],
      showDetail: false,
      transfer: {},
      treeFilter: '',
      dictTree: [],
      loadingTree: false,
      selectDict: ''
    });
    const ref_cusTable = ref()
    //  获取字典
    const initDictionary = () => {
    }
    //  查询分页参数改变处理方法
    const handlePage = ({page, pageSize}: any) => {
      state.queryPage.pageNum = page
      state.queryPage.pageSize = pageSize
      handleSearch(page, pageSize)
    }
    //  重置查询表单方法
    const handleReset = () => {
      state.queryForm = {}
      state.back_queryForm = JSON.parse(JSON.stringify(state.queryForm))
      handleSearch()
    }
    //  查询方法
    const handleSearch = (page = 1, pageSize = 10) => {
      //  添加分页参数
      const queryParams: any = {
        pageNum: page,
        pageSize: pageSize,
        dictType: state.selectDict
      }
      //  添加表单参数
      for (const [k, v] of Object.entries(state.back_queryForm)) {
        that.$util.isValue(v) ? (queryParams[k] = v) : null;
      }
      state.loading = true
      that.$api.getDictDataList(that.$util.formatGetParam(queryParams)).then((res: any) => {
        if (res.code === 200) {
          state.queryResult.tableData = res.rows
          state.queryResult.total = res.total
        } else {
          ElMessage.error(res.message)
        }
        state.loading = false
      }).catch(() => {
        state.loading = false
      })
    }
    //  点击查询按钮后
    const onSearch = () => {
      ref_cusTable.value.resetFilter()
      state.back_queryForm = JSON.parse(JSON.stringify(state.queryForm))
      state.queryPage.pageNum = 1
      handleSearch()
    }
    const onAdd = () => {
      state.transfer = {
        method: 'add',
        dictType: state.selectDict
      }
      state.showDetail = true
    }
    const onEdit = (val) => {
      state.transfer = {
        method: 'edit',
        detail: JSON.parse(JSON.stringify(val)),
        dictType: state.selectDict
      }
      state.showDetail = true
    }
    const onView = (val) => {
      state.transfer = {
        method: 'view',
        detail: JSON.parse(JSON.stringify(val))
      }
      state.showDetail = true
    }
    const initTree = () => {
      state.loadingTree = true
      state.dictTree = []
      that.$api.getDictTypeTreeSelectTree().then(res => {
        if (res.code === 200) {
          state.dictTree = res.data.map((p) => {
            p.expend = false
            p.name = p.label
            p.value = p.attachedField
            if (p.children?.length > 0) {
              p.children = p.children.map(c => {
                c.name = c.label
                c.value = c.attachedField
                return c
              })
            }
            return p
          })
        } else {
          ElMessage.error(res.message)
        }
        state.loadingTree = false
      }).catch(() => {
        state.loadingTree = false
      })
    }
    const handleTreeClick = (val) => {
      state.selectDict = val
      handleSearch()
    }
    const onDel = (val) => {
      ElMessageBox.confirm(`是否删除${val.dictLabel}?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        state.loading = true
        that.$api.delDictData(val.id).then(res => {
          if (res.code === 200) {
            ElMessage.success(res.message)
            handleSearch()
          } else {
            ElMessage.error(res.message)
            state.loading = false
          }
        }).catch(() => {
          state.loading = false
        })
      }).catch(() => {})
    }
    onMounted(() => {
      state.back_queryForm = JSON.parse(JSON.stringify(state.queryForm))
      initDictionary()
      initTree()
    })
    return {
      ref_cusTable,
      ...toRefs(state),
      handleSearch,
      handlePage,
      handleReset,
      onSearch,
      onAdd,
      onEdit,
      onView,
      handleTreeClick,
      onDel
    }
  },
})
</script>

<style scoped lang="scss">
.__normal-tree {
  width: 224px;
  margin-right: 24px;
  padding-top: 40px;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  .tree-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    align-items: center;
    .tree-parent {
      background-image: url("./dict_bg.png");
      width: 188px;
      height: 34px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 18px;
      font-family: PingFang SC-Medium, PingFang SC;
      font-weight: 500;
      color: rgba(46,184,255,0.6);
      margin-bottom: 10px;
      &.active {
        background-image: url("./dict_bg-active.png");
        width: 196px;
        height: 54px;
        color: #3EFFBB;
        text-shadow: 0px 0px 4px rgba(62,255,187,0.1);
      }
    }
    .tree-son {
      font-size: 18px;
      font-family: PingFang SC-Medium, PingFang SC;
      font-weight: 500;
      color: rgba(255,255,255,0.6);
      text-shadow: 0px 0px 4px rgba(62,255,187,0.1);
      margin-bottom: 10px;
      align-self: flex-start;
      padding-left: 76px;
      &.active {
        color: #3EFFBB;
      }
    }
  }
}
</style>