<script setup lang="ts">
import { cloneDeep } from 'lodash-es'

import dictManagementApi from '#/api/modules/setting/dictManagement'
import { delConfirm } from '#/utils/tool'
import XbTableClass from '#/utils/xbTable'

import column from './column.jsx'

const props = defineProps({
  showSub: {
    type: Boolean,
    default: false,
  },
  subData: {
    type: Object,
    default: () => ({}),
  },
})

const emit = defineEmits(['update:showSub', 'onRefresh'])

const show = computed({
  get() {
    return props.showSub
  },
  set(val) {
    emit('update:showSub', val)
  },
})

const xbTable = reactive(
  new XbTableClass({
    column: column({
      removeSub,
    }),
    page: {
      size: 20,
      current: 1,
      total: 0,
    },
    data: [],
  }),
)
provide('xbTable', xbTable)
let initDate: anyObj[] = []
async function getListSysDict() {
  const res = await dictManagementApi.getSysDictDataList({
    typeId: props.subData.id,
  })
  initDate = cloneDeep(res)
  xbTable.table.data = [...res]
}

// async function updateState(row: anyObj) {
//     row.loading = true
//     try {
//         let { data: res } = await changeDictDataStatus({
//             id: row.id,
//             status: row.status === 0 ? 1 : 0,
//         })
//         return true
//     } catch (err) {
//         return false
//     } finally {
//         row.loading = false
//     }
// }

// function handleClick(type: Number, row: anyObj) {
//     switch (type) {
//         case 1:
//             if (row.id) {
//                 editDictData(row).then(() => getListSysDict())
//             } else {
//                 addDictData({ typeId: props.subData.id, ...row }).then(() => getListSysDict())
//             }
//             break
//         case 0:
//             delDictData(row).then(() => getListSysDict())
//             break
//     }
// }

function addSub() {
  xbTable.table.data?.push({
    value: '',
    remark: '',
    sort: 0,
    code: '',
    status: 0,
  })
}

function removeSub(sub: anyObj) {
  xbTable.table.data?.splice(xbTable.table.data.indexOf(sub), 1)
}

function saveSub() {
  if (xbTable.table.data?.length === 0) {
    ElMessage.error('数据不能为空')
    return
  }
  if (xbTable.table.data?.some((i) => i.code === '' || i.value === '')) {
    ElMessage.error('编码或值不能为空')
    return
  }
  const params = xbTable.table.data?.map((i) =>
    Object.assign(i, { typeId: props.subData.id }),
  )
  dictManagementApi
    .putDictDataSaveList(params!)
    .then(() => (show.value = false))
}
async function onClose() {
  let flag = false
  const data = xbTable.table.data as any
  if (initDate.length === data?.length) {
    for (const [i, element] of initDate.entries()) {
      for (const key in element) {
        if (element[key] !== data[i][key]) {
          flag = true
          break
        }
      }
    }
  } else {
    flag = true
  }
  if (flag) {
    await delConfirm(true)
  }
  show.value = false
}
watch(
  () => props.showSub,
  async (newVal) => {
    show.value = newVal
    if (newVal) {
      getListSysDict()
    }
  },
)
</script>

<template>
  <el-dialog
    v-model="show"
    :title="subData.name"
    width="60vw"
    top="10vh"
    class="box"
    destroy-on-close
    :before-close="onClose"
  >
    <el-scrollbar height="500px">
      <Table class="page-table" :pagination="false" />
      <div type="text" class="addSub-btn" @click="addSub">新增子集</div>
    </el-scrollbar>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="onClose">取消</el-button>
        <el-button type="primary" @click="saveSub">保存</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style scoped lang="scss">
.addSub-btn {
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 30px auto;
  font-family: SourceHanSansSC-Medium, SourceHanSansSC;
  font-weight: 500;
  color: #4f87f5;
  cursor: pointer;

  .icon {
    margin-right: 5px;
  }
}

.page-table {
  :deep(.el-button) {
    justify-content: flex-start;
    padding: 0 3px;
  }
}
</style>
