<script setup lang="tsx">
import { ContentWrap } from '../../../components/ContentWrap'
import { useI18n } from '../../../hooks/web/useI18n'
import {
  addDept,
  delDeptTree,
  getDeptTree,
  queryDept,
  updateDept
} from '../../../api/system-config/department'
import type { DepartmentItem } from '../../../api/system-config/department/types'
import { reactive, ref, toRaw, unref, watch } from 'vue'
import Write from './components/Write.vue'
import { FormSchema } from '../../../components/Form'
import { BaseButton } from '../../../components/Button'
import { ElTree } from 'element-plus'
import { getCodeByType } from '../../../utils'
import DistrictSelect from '../../../business-components/DistrictSelect.vue'

const { t } = useI18n()

const district = ref('')

const formSchema = reactive<FormSchema[]>([
  {
    field: 'pid',
    label: '上级部门',
    component: 'TreeSelect',
    componentProps: {
      nodeKey: 'id',
      props: {
        label: 'name'
      },
      checkStrictly: true
    },
    optionApi: async () => {
      const res = await getDeptTree({})
      return res.data
    }
  },
  {
    field: 'deptName',
    label: '部门名称',
    component: 'Input'
  },
  {
    field: 'deptType',
    label: '部门分类',
    component: 'Select',
    componentProps: {
      multiple: false,
      collapseTags: true,
      maxCollapseTags: 1
    },
    optionApi: async () => {
      return getCodeByType('BUSINESS_DEPT')
    }
  },
  {
    field: 'deptCode',
    label: '部门编号',
    component: 'Input'
  },
  {
    field: 'districtNo',
    label: '行政区划',
    formItemProps: {
      slots: {
        default: () => {
          return <DistrictSelect style="width: 100%" v-model={district.value}></DistrictSelect>
        }
      }
    }
  },
  {
    field: 'telephone',
    label: '联系电话',
    component: 'Input'
  },
  {
    field: 'location',
    label: '地点',
    component: 'Input',
    colProps: {
      span: 24
    }
  },
  {
    field: 'remark',
    label: '部门描述',
    component: 'Input',
    componentProps: {
      type: 'textarea',
      rows: 5
    },
    colProps: {
      span: 24
    }
  }
])

const currentRow = ref<any>(null)
const actionType = ref('add')

//部门树相关
const treeEl = ref<typeof ElTree>()

const currentDepartment = ref('')
watch(
  () => currentDepartment.value,
  (val) => {
    unref(treeEl)!.filter(val)
  }
)

const departmentList = ref<DepartmentItem[]>([])
const currentNodeKey = ref('')
const defaultExpandedKeys = ref()
const fetchDepartment = async () => {
  const res = await getDeptTree({})
  departmentList.value = res.data
  if (res.data.length) {
    defaultExpandedKeys.value = res.data.map((i) => i.id)
  }
}
fetchDepartment()

const filterNode = (value: string, data: any) => {
  if (!value) return true
  return data?.name.includes(value)
}

const setCurrentRow = async (data: DepartmentItem) => {
  actionType.value = 'edit'
  lastVersion.value = null
  const res = await queryDept({ deptId: data.id })
  currentRow.value = res?.data || {}
  currentNodeKey.value = data.id
  district.value = res?.data.districtNo
}

const del = (_node, row) => {
  ElMessageBox.confirm('确定删除？', t('common.reminder'), {
    confirmButtonText: t('common.ok'),
    cancelButtonText: t('common.cancel'),
    type: 'warning'
  })
    .then(async () => {
      await delDeptTree({ deptId: row.id })
      await fetchDepartment()
    })
    .catch(() => {})
}
const writeRef = ref<ComponentRef<typeof Write>>()

const AddAction = (_event, _node, row) => {
  writeRef.value?.clearForm()
  currentRow.value = {
    pid: toRaw(row).id
  }
  actionType.value = 'add'
}

const saveLoading = ref(false)
// 记录前一个编辑的版本 用于再次编辑时 version字段可以+1
const lastVersion = ref<Recordable | null>(null)

const save = async () => {
  const write = unref(writeRef)
  const formData = await write?.submit()
  let res
  if (formData) {
    const data: Recordable = {
      ...formData,
      districtNo: district.value
    }
    saveLoading.value = true
    if (actionType.value === 'edit') {
      if (lastVersion.value) {
        data.version = lastVersion.value.version + 1
      }
      res = await updateDept({
        ...data,
        deptId: currentRow.value.deptId
      })
    } else {
      delete data.deptId
      res = await addDept(data)
    }
    saveLoading.value = false

    const { success } = res
    if (success) {
      await fetchDepartment()
      // 新增操作时 初始化表单
      if (actionType.value !== 'edit') {
        writeRef.value?.clearForm()
        district.value = ''
        lastVersion.value = null
      } else {
        lastVersion.value = data
      }
    }
  }
}
</script>

<template>
  <div class="flex w-100% h-100% overflow-hidden">
    <ContentWrap class="w-300px h-100% !overflow-y-auto">
      <div class="flex justify-center items-center">
        <div class="flex-1">{{ t('userDemo.departmentList') }}</div>
        <el-input
          v-model="currentDepartment"
          class="flex-[2]"
          :placeholder="t('userDemo.searchDepartment')"
          clearable
        />
      </div>
      <el-divider />
      <el-tree
        ref="treeEl"
        :data="departmentList"
        :default-expanded-keys="defaultExpandedKeys"
        :expand-on-click-node="false"
        highlight-current
        node-key="id"
        :current-node-key="currentNodeKey"
        :props="{
          label: 'name'
        }"
        :filter-node-method="filterNode"
        @current-change="setCurrentRow"
      >
        <template #default="{ node, data }">
          <div
            :title="data.name"
            class="whitespace-nowrap overflow-ellipsis overflow-hidden flex items-center"
          >
            <div class="overflow-hidden text-ellipsis">{{ data.name }}</div>
            <img
              @click.stop="AddAction($event, node, data)"
              class="add"
              src="../../../assets/imgs/add.png"
              alt=""
            />
            <img
              @click.stop="del(node, data)"
              class="del"
              src="../../../assets/imgs/del.png"
              alt=""
            />
          </div>
        </template>
      </el-tree>
    </ContentWrap>
    <ContentWrap class="flex-[3] ml-20px">
      <Write ref="writeRef" :form-schema="formSchema" :current-row="currentRow" class="w-700px" />
      <BaseButton type="primary" :loading="saveLoading" @click="save" class="ml-80px">
        {{ t('exampleDemo.save') }}
      </BaseButton>
    </ContentWrap>
  </div>
</template>

<style lang="less" scoped>
.detpTree {
  overflow: auto;
}

.del {
  display: none;
  width: 16px;
  height: 16px;
}

.add {
  display: none;
  width: 16px;
  height: 16px;
  margin-left: 6px;
}

:deep(.el-tree-node__content) {
  &:hover {
    .del {
      display: block;
      width: 16px;
      height: 16px;
    }

    .add {
      display: block;
      width: 16px;
      height: 16px;
      margin-right: 4px;
    }
  }
}
</style>
