<script lang="ts" setup name="planlogAdd">
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { IOptions } from './plan_interface'
import userListDialog from './components/userListDialog.vue'
import { SCHEDULE } from '@/utils/scheduleDict'
import useUserStore from '@/store/modules/user.ts'
import {
  getListDetail,
  getListLogAdd,
  getListLogDetail,
  getListLogupdate,
  getPlanIdList,
} 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 { name } = useUserStore()
const ruleFormRef = ref<FormInstance>()
const formInline = ref({
  improveMethod: '',
  logNo: '',
  preparer: name || '',
  problems: '',
  planId: '',
  remark: '',
  trainAddress: '',
  trainContent: '',
  trainEffect: '',
  trainHour: '',
  trainName: '',
  trainNumber: '',
  trainPerson: '',
  trainStaffList: [],
  trainTime: '',
})
// 主管部门下拉框
const options = ref<IOptions[]>([])
const dialogVisible = ref(false)
// 下面列表用的
const trainList = ref([])
const columns = [
  // { text: '学员名称', value: 'name' },
  { text: '单位名称', value: 'company', required: true },
  { text: '技术职称', value: 'technologyJob', required: true },
  { text: '签到时间', value: 'signTime', required: true },
  { text: '考核结果', value: 'examResult', required: true },
]
// 校验规则
const rules = ref({
  logNo: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
  preparer: [{ required: true, message: '填表人不能为空', trigger: 'blur' }],
  planId: [{ required: true, message: '计划编号必选', trigger: 'blur' }],
  trainName: [{ 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' }],
  trainEffect: [{ required: true, message: '培训效果不能为空', trigger: 'blur' }],
  problems: [{ required: true, message: '存在问题不能为空', trigger: 'blur' }],
  improveMethod: [{ required: true, message: '改进措施不能为空', trigger: 'blur' }],
}) // 表单验证规则
const userListRef = ref()
const addPersonList = ref({
  company: '',
  examResult: '',
  name: '',
  remark: '',
  signTime: '',
  technologyJob: '',
  planId: 0,
  staffId: 0,
})
const SelectionList = ref([])
const ListDetail = ref([])
// 控制是否显示输入框开关
const isNameShow = ref(true)
// 获取到组织信息
const getDept = () => {
  const params = {
    createTime: '',
    deptId: 0,
    director: '',
    effectiveCompany: '',
    formId: SCHEDULE.TRAIN_APPROVAL,
    trainTime: '',
  }
  getPlanIdList(params).then((response) => {
    options.value = response.data
  })
}
getDept()
// 初始化router
const $router = useRouter()
// 关闭新增页面的回调
const close = () => {
  $router.back()
}
const addRoow = () => {
  if (formInline.value.planId === '') {
    return ElMessage.warning('还未选择计划编号')
  }
  const object = {
    company: '',
    examResult: '',
    name: '',
    remark: '',
    signTime: '',
    technologyJob: '',
    planId: 0,
    staffId: 0,
    isNameShow: false,
  }
  trainList.value.push(object)
}
// 点击关闭
const handleClose = () => {
  dialogVisible.value = false
}
// 选择人员编号
const selectChange = (e: any) => {
  const id = options.value.filter(item => item.id === e)[0].id
  getListDetail({ id }).then((res) => {
    ListDetail.value = res.data.trainStaffList
    res.data.preparer = name
    formInline.value = { ...res.data }
    formInline.value.planId = e
  })
}
// 删除行
const deleteList = () => {
  trainList.value = trainList.value.filter(
    (item) => {
      return !SelectionList.value.includes(item)
    },
  )
}
const handleSelectionChange = (e: any) => {
  SelectionList.value = e
}
const addPersonListChange = (e: any) => {
  addPersonList.value = ListDetail.value.filter(item => item.staffId === e)[0]
}
if (infoId.value && infoId.value !== '') {
  getListLogDetail({ id: infoId.value }).then((res) => {
    formInline.value = res.data
    trainList.value = formInline.value.trainStaffList
  })
}
// 双击表格中默认显示的name
const dblclickName = (row: object) => {
  row.isNameShow = true
}
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') {
          getListLogAdd(formInline.value).then((res) => {
            if (res.code === 200) {
              close()
            }
          })
        }
        else if (buttonType === '提交' && pageType.value === 'edit') {
          formInline.value.trainStaffList = trainList.value
          formInline.value.trainStaffList.map((item) => {
            delete item.updateTime
            delete item.createTime
          })
          formInline.value.id = infoId.value
          getListLogupdate(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 listIndex = ref(0)
// 选择人员
const selectPerson = (index: number) => {
  userListRef.value.initDialog()
  listIndex.value = index
}
// 选择完负责人的函数
const confirmPerson = (object: object) => {
  if (!trainList.value.includes(object)) {
    trainList.value[listIndex.value] = object
  }
  else {
    ElMessage.warning('该学员已经存在')
    trainList.value.splice(listIndex.value, 1)
  }
}
</script>

<template>
  <app-container>
    <detail-page :title="`培训记录-${textMap[pageType]}`">
      <template #btns>
        <el-button
          v-if=" pageType !== 'detail'"
          type="primary"
          @click="getAddList(ruleFormRef, '提交')"
        >
          提交
        </el-button>
        <el-button v-if=" pageType === 'detail'" v-print="printObj" type="primary" @click="getAddList(ruleFormRef, '打印')">
          打印
        </el-button>
        <el-button v-if=" pageType === 'detail'" type="primary" @click="pageType = 'edit'">
          编辑
        </el-button>
        <el-button type="info" @click="close">
          关闭
        </el-button>
      </template>
      <el-form
        ref="ruleFormRef"
        :model="formInline"
        class="demo-form-inline"
        label-position="right"
        label-width="100"
        :rules="rules"
      >
        <el-row :gutter="24" class="marg">
          <el-col :span="6">
            <el-form-item label="编号:" prop="logNo">
              <el-input
                v-model="formInline.logNo"
                :placeholder="pageType === 'detail' ? '无' : '请输入编号'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="填表人:" prop="preparer">
              <el-input
                v-model="formInline.preparer"
                :placeholder="pageType === 'detail' ? '无' : '请输入填表人'"
                :disabled="pageType === 'detail'"
              />
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item v-if="infoId === ''" label="计划编号:" prop="planId">
              <el-select
                v-model="formInline.planId"
                clearable
                placeholder="计划编号"
                size="default"
                :disabled="pageType === 'detail'"
                @change="selectChange"
              >
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.planName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="培训名称:" prop="trainName">
              <el-input
                v-model="formInline.trainName"
                :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="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-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="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-row>
        <el-row :gutter="24" class="marg">
          <el-col :span="12">
            <el-form-item label="培训地点:" prop="trainAddress">
              <el-input
                v-model="formInline.trainAddress"
                :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="培训效果:" prop="trainEffect">
              <el-input
                v-model="formInline.trainEffect"
                :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="存在问题:" prop="problems">
              <el-input
                v-model="formInline.problems"
                :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="改进措施:" prop="improveMethod">
              <el-input
                v-model="formInline.improveMethod"
                :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" :disabled="pageType === 'detail'" @click="deleteList">
          删除行
        </el-button>
        <el-button v-if="pageType !== 'detail'" type="primary" :disabled="pageType === 'detail'" @click="addRoow">
          增加行
        </el-button>
      </template>
      <el-table
        :data="trainList"
        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 align="center" label="学员名称">
          <template #header>
            <span style="color: red;">*</span><span>学员名称</span>
          </template>
          <template #default="scope">
            <el-input v-model="scope.row.name" placeholder="请输入或者选择" class="input">
              <template #append>
                <el-button size="small" :disabled="pageType === 'detail'" @click="selectPerson(scope.$index)">
                  选择
                </el-button>
              </template>
            </el-input>
          </template>
        </el-table-column>
        <el-table-column v-for="(item, index) in columns" :key="index" align="center" :label="item.text" :prop="item.value">
          <template #header>
            <span v-show="item.required" style="color: red;">*</span><span>{{ item.text }}</span>
          </template>
          <template #default="scope">
            <el-input v-model="scope.row[item.value]" :placeholder="`${item.text}`" class="input" />
          </template>
        </el-table-column>
      </el-table>
    </detail-block>
  </app-container>
  <!-- 选择用户列表组件 -->
  <user-list-dialog ref="userListRef" :list="formInline.trainStaffList" @add="confirmPerson" />
</template>

