<template>
  <div class="h-full flex">
    <div class="p-5 w-60 pr-0">
      <div class="bg-white w-full h-full shadow-md rounded-md flex flex-col const-left">
        <el-table ref="dictionaryTableRef" :data="dictionaryTableData" border highlight-current-row
          @current-change="dictionaryHandleCurrentChange" style="width: 100%;height: 100%;">
          <el-table-column prop="name" label="字典编码" align="center" />
        </el-table>
      </div>
    </div>
    <div class="flex-1 p-5 overflow-auto">
      <div class="bg-white w-full h-full shadow-md rounded-md flex flex-col">
        <div class="tableHeader">
          <div>字典编码-{{ currentRow?.name }}</div>
          <el-button type="primary" @click="showDialogFormVisible()" :disabled="!currentRow.id">新增参数</el-button>
        </div>
        <div class="flex-1 p-3">
          <el-table ref="dictionaryTableRef" :data="tableData" v-loading="AllLoading.tableDataLoading" border
            style="width: 100%;height: 100%;">
            <el-table-column type="selection" width="55" />
            <el-table-column prop="name" label="字典名称" align="center" />
            <el-table-column prop="seq" label="排序" align="center" />
            <el-table-column label="操作" width="100px">
              <template #default="{ row, $index }">
                <dv class="operation">
                  <el-icon @click="deteleItem(row)">
                    <Delete color="red" />
                  </el-icon>
                </dv>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </div>

    <!-- 弹窗 -->
    <el-dialog title="新增参数" v-model="AllVisible.dialogFormVisible" width="500" align-center
      :before-close="handleClose">
      <div>
        <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
          <el-form-item label="字典名称" prop="name">
            <el-input v-model="form.name" placeholder="请输入字典名称"></el-input>
          </el-form-item>
          <el-form-item label="排序" prop="seq">
            <el-input-number v-model="form.seq" :step="2" placeholder="请输入排序" controls-position="right" style="width: 100%;" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="submitForm(formRef, false)" v-loading="AllLoading.dialogFormLoading">保
            存</el-button>
          <el-button type="primary" @click="submitForm(formRef, true)"
            v-loading="AllLoading.dialogFormLoading">保存并新增</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, inject } from 'vue';
import { Delete } from '@element-plus/icons-vue'
import { FormInstance, FormRules, ElMessageBox, ElTable } from 'element-plus'
import { GETLISTBYCODE, GETTYPE, UNDATELIST, DELETELIST } from './api'
import { post } from "@/utils/request";
import { getFromValue, resetFromValue } from '@/utils/tools'

type dictionaryTab = {
  id: string | number
  name: string
}

interface RuleForm {
  name: string,
  seq: string | number,
  id: string | number,
  code: string
}

const globalPopup = inject<GlobalPopup>('globalPopup')
const dictionaryTableRef = ref<InstanceType<typeof ElTable>>()
const currentRow: any = ref({})
const dictionaryTableData = ref<dictionaryTab[]>([])
const tableData = ref<any[]>([])
const formRef = ref<FormInstance>()
const form = reactive<RuleForm>({
  id: '',
  code: '',
  name: '',
  seq: ''
})
const rules = reactive<FormRules<RuleForm>>({
  name: [{ required: true, message: '请输入字典名称', trigger: 'change' }],
  seq: [{ required: true, message: '请输入排序', trigger: 'change' }]
})
const AllLoading = reactive({
  tableDataLoading: false,
  dialogFormLoading: false
})
const AllVisible = reactive({
  dialogFormVisible: false
})

function deteleItem(data: any) {
  ElMessageBox.confirm(
    `确定删除【${data.name}】字典吗？`, '',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(() => {
      post(DELETELIST, { id: data.id, code: data.code }).then(res => {
        if (res.code != 'ok') {
          globalPopup?.showError(res.msg)
          return
        }
        globalPopup?.showSuccess('删除成功')
        getTableList()
      })
    })
}

function showDialogFormVisible() {
  let newForm = resetFromValue(form)
  newForm.code = currentRow.value.id
  Object.assign(form, newForm)
  AllVisible.dialogFormVisible = true
  console.log(form)
}

async function submitForm(formEl: FormInstance | undefined, flag: boolean) {
  if (!formEl) return
  await formEl.validate((valid) => {
    if (valid) {
      updateList(getFromValue(form), flag)
    }
  })
}

function updateList(data: any, flag: boolean) {
  AllLoading.dialogFormLoading = true
  post(UNDATELIST, { ...data }).then((_res) => {
    let newForm = resetFromValue(form)
    newForm.code = currentRow.value.id
    Object.assign(form, newForm)
    globalPopup?.showSuccess ('保存成功')
    getTableList()
    AllLoading.dialogFormLoading = false
    AllVisible.dialogFormVisible = flag
  }).catch((_err) => {
    AllLoading.dialogFormLoading = false
  })
}

function getDataType() {
  post(GETTYPE, {}).then((res) => {
    dictionaryTableData.value = res.data
    dictionarySetCurrent(dictionaryTableData.value[0])
  })
}

function getTableList() {
  const { id } = currentRow.value
  post(GETLISTBYCODE, { code: id }).then((res) => {
    tableData.value = res.data
  })
}

function handleClose(done: any) {
  done()
}

function dictionaryHandleCurrentChange(val: any) {
  currentRow.value = val;
  getTableList()
}

function dictionarySetCurrent(row?: dictionaryTab) {
  dictionaryTableRef.value!.setCurrentRow(row)
}

onMounted(() => {
  getDataType()
});
</script>

<style lang="scss" scoped>
$borderColor : #F4F4F4;
$titleBack : #FBFBFB;
$themeColor : #075985;

.const-left {
  .const-leftTile {
    text-align: center;
    background: $titleBack;
    padding: 0.85rem 0;
  }

  .const-leftItem {
    width: 100%;
    text-align: center;
    padding: 0.85rem 0;
    cursor: pointer;
  }

  .ons {
    background: $themeColor;
    color: #fff;
  }

  .border-bottom {
    border-bottom: 1px solid $borderColor;
  }
}

.tableHeader {
  display: flex;
  width: 100%;
  justify-content: space-between;
  align-items: center;
  padding: 10px;
  background-color: #F5F7FA;
}
</style>