<script lang="ts" setup name="PlanAdd">
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import userListDialog from '../person/components/userListDialog.vue'
import type { IOptions } from './plan_interface'
import DeptSelect from '@/components/DeptSelect/index.vue'
import { SCHEDULE } from '@/utils/scheduleDict'
import {
  getDeptTree,
  getListDetail,
  getListSave,
  getListSubmit,
  getListUpdate,
} from '@/api/system/plan'
const loading = ref(false) // 表单加载状态
const infoId = ref('') // id
const pageType = ref('add') // 页面类型: add,edit, detail
const buttonLoading = ref(false) // 按钮加载状态
const textMap: { [key: string]: string } = {
  edit: '编辑',
  add: '新建',
  detail: '详情',
} // 字典
// 从路由中获取页面类型参数
const $route = useRoute()
if ($route.params && $route.params.type) {
  pageType.value = $route.params.type as string
  if ($route.params.id) {
    infoId.value = $route.params.id as string
  }
}
const formInline = ref({
  createTime: null,
  deptId: null,
  deptName: null,
  director: null,
  effectiveCompany: null,
  id: null,
  planName: null,
  planNo: null,
  remark: null,
  trainAddress: null,
  trainContent: null,
  trainHour: null,
  trainNumber: null,
  trainPerson: null,
  trainStaffList: [],
  trainTime: null,
})
const addId = ref('') // 保存后的id
const ruleFormRef = ref<FormInstance>()
const columns = [
  { text: '学员名称', value: 'name' },
  { text: '单位名称', value: 'company' },
  { text: '技术职称', value: 'technologyJob' },
  { text: '签到时间', value: 'signTime', type: '下拉' },
]
const dialogVisible = ref(false)
const addPersonList = ref({
  company: '',
  examResult: '',
  id: 0,
  name: '',
  remark: '',
  signTime: '',
  staffId: 0,
  technologyJob: '',
})
const SelectionList = ref([])
// 校验规则
const rules = ref({
  planNo: [{ required: true, message: '计划编号不能为空', trigger: 'blur' }],
  planName: [{ required: true, message: '培训名称不能为空', trigger: 'blur' }],
  trainPerson: [
    { required: true, message: '培训对象不能为空', trigger: 'blur' },
  ],
  trainNumber: [
    { required: true, message: '培训人数不能为空', trigger: 'blur' },
  ],
  trainHour: [{ required: true, message: '培训学时不能为空', trigger: 'blur' }],
  trainTime: [{ required: true, message: '培训时间不能为空', trigger: 'blur' }],
  trainAddress: [
    { required: true, message: '培训地点不能为空', trigger: 'blur' },
  ],
  deptId: [{ required: true, message: '主管部门不能为空', trigger: 'blur' }],
  effectiveCompany: [
    { required: true, message: '实施单位不能为空', trigger: 'blur' },
  ],
  director: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
  trainContent: [
    { required: true, message: '培训内容不能为空', trigger: 'blur' },
  ],
}) // 表单验证规则
// 新增校验规则
const addRules = ref({
  name: [{ required: true, message: '学员名称不能为空', trigger: 'blur' }],
  company: [{ required: true, message: '单位名称不能为空', trigger: 'blur' }],
  technologyJob: [
    { required: true, message: '技术职称不能为空', trigger: 'blur' },
  ],
  signTime: [{ required: true, message: '签到时间不能为空', trigger: 'blur' }],
}) // 表单验证规则
// 初始化router
const $router = useRouter()
// 关闭新增页面的回调
const close = () => {
  $router.back()
}
const userListRef = ref()
// 选择人员
const selectPerson = () => {
  userListRef.value.initDialog()
}
const addRoow = () => {
  Object.keys(addPersonList.value).forEach(
    key => (addPersonList.value[key] = ''),
  )
  dialogVisible.value = true
}
// 点击关闭
const handleClose = () => {
  dialogVisible.value = false
}
// 点击弹窗的完成追加到表格数组中
const addPushList = () => {
  formInline.value.trainStaffList.push(
    JSON.parse(JSON.stringify(addPersonList.value)),
  )
  handleClose()
}
// 删除行
const deleteList = () => {
  formInline.value.trainStaffList = formInline.value.trainStaffList.filter(
    (item) => {
      return !SelectionList.value.includes(item)
    },
  )
}
// 多选框选择
const handleSelectionChange = (e: any) => {
  SelectionList.value = e
}
// 选择完负责人的函数
const confirmPerson = (object: object) => {
  console.log(object)
  formInline.value.director = object.name
}
if (infoId.value && infoId.value !== '') {
  getListDetail({ id: infoId.value }).then((res) => {
    formInline.value = res.data
  })
}
// 点击提交
const getAddList = async (
  formEl: FormInstance | undefined,
  buttonType: string,
) => {
  if (!formEl) {
    return
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(`确认${buttonType}吗？`, '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        if (buttonType === '提交' && pageType.value !== 'edit') {
          if (addId.value === '') {
            ElMessage.warning('请先保存')
          }
          else {
            getListSubmit({ id: addId.value, formId: SCHEDULE.TRAIN_APPROVAL }).then((res) => {
              if (res.code === 200) {
                close()
              }
            })
          }
        }
        else if (buttonType === '提交' && pageType.value === 'edit') {
          formInline.value.trainStaffList.map((item) => {
            delete item.updateTime
            delete item.createTime
          })
          formInline.value.id = infoId.value
          getListUpdate(formInline.value).then((res) => {
            if (res.code === 200) {
              close()
            }
          })
        }
        else {
          // 打印
          const printObj = ref({
            id: 'print', // 需要打印元素的id
            popTitle: '证书报告模板', // 打印配置页上方的标题
            extraHead: '', // 最上方的头部文字，附加在head标签上的额外标签，使用逗号分割
            preview: false, // 是否启动预览模式，默认是false
            standard: '',
            extarCss: '',
          })
        }
      })
    }
  })
}
// 点击保存
const preserve = async (formEl: FormInstance | undefined) => {
  if (!formEl) {
    return
  }
  await formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm('确认保存吗？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        getListSave(formInline.value).then((res) => {
          if (res.code === 200) {
            addId.value = res.data.id
            ElMessage.success('保存成功！')
          }
        })
      })
    }
  })
}
</script>

<template>
  <app-container>
    <detail-page :title="`培训计划-${textMap[pageType]}`">
      <template #btns>
        <el-button
          v-print="pageType === 'detail' ? printObj : ''"
          type="primary"
          @click="
            getAddList(ruleFormRef, pageType === 'detail' ? '打印' : '提交')
          "
        >
          {{ pageType === 'detail' ? '打印' : '提交' }}
        </el-button>
        <el-button
          type="primary"
          @click="preserve(ruleFormRef)"
        >
          保存
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <el-form
        ref="ruleFormRef"
        :model="formInline"
        class="demo-form-inline"
        :rules="rules"
        label-width="auto"
        label-position="right"
      >
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="计划编号:" prop="planNo">
              <el-input
                v-model="formInline.planNo"
                :placeholder="pageType === 'detail' ? '无' : '请输入计划编号'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="培训名称:" prop="planName">
              <el-input
                v-model="formInline.planName"
                :placeholder="pageType === 'detail' ? '无' : '请输入培训名称'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="培训对象:" prop="trainPerson">
              <el-input
                v-model="formInline.trainPerson"
                :placeholder="pageType === 'detail' ? '无' : '请输入培训对象'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="培训人数:" prop="trainNumber">
              <el-input
                v-model="formInline.trainNumber"
                :placeholder="pageType === 'detail' ? '无' : '请输入培训人数'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="培训时间:" prop="trainTime">
              <el-date-picker
                v-model="formInline.trainTime"
                type="datetime"
                placeholder="培训时间"
                format="YYYY/MM/DD HH:mm:ss"
                value-format="YYYY-MM-DD h:m:s"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="培训学时:" prop="trainHour">
              <el-input
                v-model="formInline.trainHour"
                :placeholder="pageType === 'detail' ? '无' : '请输入培训学时'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="主管部门:" prop="deptId">
              <dept-select
                ref="deptSelect"
                v-model="formInline.deptId"
                :disabled="pageType === 'detail'"
                :dept-show="true"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="实施单位:" prop="effectiveCompany">
              <el-input
                v-model="formInline.effectiveCompany"
                :placeholder="pageType === 'detail' ? '无' : '请输入实施单位'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="负责人:" prop="director">
              <el-input
                v-model="formInline.director"
                :placeholder="pageType === 'detail' ? '无' : '请输入负责人'"
                :disabled="pageType === 'detail'"
              >
                <template #append>
                  <el-button
                    size="small"
                    :disabled="pageType === 'detail'"
                    @click="selectPerson"
                  >
                    选择
                  </el-button>
                </template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="培训地点:" prop="trainAddress">
              <el-input
                v-model="formInline.trainAddress"
                :placeholder="pageType === 'detail' ? '无' : '请输入培训地点'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="培训内容:" prop="trainContent">
              <el-input
                v-model="formInline.trainContent"
                :placeholder="pageType === 'detail' ? '无' : '请输入培训内容'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="12">
            <el-form-item label="备注:">
              <el-input
                v-model="formInline.remark"
                :placeholder="pageType === 'detail' ? '无' : '请输入备注'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
    <detail-block title="人员信息">
      <template #btns>
        <el-button v-if="pageType !== 'detail'" type="info" @click="deleteList">
          删除行
        </el-button>
        <el-button v-if="pageType !== 'detail'" type="primary" @click="addRoow">
          增加行
        </el-button>
      </template>
      <el-table
        :data="formInline.trainStaffList"
        border
        style="width: 100%;"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column align="center" label="序号" width="80" type="index" />
        <el-table-column
          v-for="item in columns"
          :key="item.value"
          :prop="item.value"
          :label="item.text"
        />
      </el-table>
    </detail-block>
  </app-container>
  <el-dialog
    v-model="dialogVisible"
    title="添加人员信息"
    width="30%"
    :before-close="handleClose"
  >
    <el-form
      ref="addPersonListForm"
      label-position="left"
      label-width="100px"
      :model="addPersonList"
      style="max-width: 460px;"
      :rules="addRules"
    >
      <el-form-item label="学员名称" prop="name">
        <el-input v-model="addPersonList.name" />
      </el-form-item>
      <el-form-item label="单位名称" prop="company">
        <el-input v-model="addPersonList.company" />
      </el-form-item>
      <el-form-item label="技术职称" prop="technologyJob">
        <el-input v-model="addPersonList.technologyJob" />
      </el-form-item>
      <el-form-item label="签到时间" prop="signTime">
        <el-date-picker
          v-model="addPersonList.signTime"
          type="datetime"
          placeholder="签到时间"
          format="YYYY/MM/DD HH:mm:ss"
          value-format="YYYY-MM-DD h:m:s"
          :disabled="pageType === 'detail'"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="addPushList">
          完成
        </el-button>
        <el-button @click="dialogVisible = false">
          取消
        </el-button>
      </div>
    </template>
  </el-dialog>
  <!-- 选择用户列表组件 -->
  <user-list-dialog ref="userListRef" @add="confirmPerson" />
</template>
