<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 PlanListDialog from './components/planListDialog.vue'
import { SCHEDULE } from '@/utils/scheduleDict'
import useUserStore from '@/store/modules/user.ts'
import {
  getListDetail,
  getListLogAdd,
  getListLogDetail,
  getListLogupdate,
} 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: '',
  id: '',
  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', 'change'] }],
  preparer: [{ required: true, message: '填表人不能为空', trigger: ['blur', 'change'] }],
  planId: [{ required: true, message: '计划编号必选', trigger: ['blur', 'change'] }],
  trainName: [{ required: true, message: '培训名称不能为空', trigger: ['blur', 'change'] }],
  trainPerson: [{ required: true, message: '培训对象不能为空', trigger: ['blur', 'change'] }],
  trainNumber: [{ required: true, message: '培训人数不能为空', trigger: ['blur', 'change'] }],
  trainHour: [{ required: true, message: '培训学时不能为空', trigger: ['blur', 'change'] }],
  trainTime: [{ required: true, message: '培训时间不能为空', trigger: ['blur', 'change'] }],
  trainAddress: [{ required: true, message: '培训地点不能为空', trigger: ['blur', 'change'] }],
  trainEffect: [{ required: true, message: '培训效果不能为空', trigger: ['blur', 'change'] }],
  problems: [{ required: true, message: '存在问题不能为空', trigger: ['blur', 'change'] }],
  improveMethod: [{ required: true, message: '改进措施不能为空', trigger: ['blur', 'change'] }],
  trainContent: [{ required: true, message: '培训内容不能为空', trigger: ['blur', 'change'] }],
}) // 表单验证规则
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)
// 初始化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: '',
    staffId: '',
    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
}
// 点击删除和编辑的参数类型
interface itemReturn {
  staffId: string
}
const addPersonListChange = (e: string) => {
  addPersonList.value = ListDetail.value.filter((item: itemReturn) => item.staffId === e)[0]
}
if (infoId.value && infoId.value !== '') {
  getListLogDetail({ id: infoId.value }).then((res) => {
    formInline.value = res.data
    trainList.value = formInline.value.trainStaffList
  })
}
// 点击删除和编辑的参数类型
interface rowReturn {
  isNameShow: boolean
  id: string
  planName: string
}
// 双击表格中默认显示的name
const dblclickName = (row: rowReturn) => {
  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) {
              ElMessage.success('提交成功')
              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) {
              ElMessage.success('提交成功')
              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 planListDialog = ref()
// 选择培训数据
const selectPlanId = () => {
  planListDialog.value.initDialog()
}
// 选择培训数据完成之后
const confirmPlan = (data: rowReturn) => {
  getListDetail({ id: data.id }).then((res) => {
    ListDetail.value = res.data.trainStaffList
    res.data.preparer = name
    formInline.value = { ...res.data }
    formInline.value.planId = data.id
    formInline.value.trainName = data.planName
  })
}
// 选择完负责人的函数
const confirmPerson = (object: rowReturn) => {
  if (!trainList.value.includes(object)) {
    trainList.value[listIndex.value] = object
    trainList.value[listIndex.value].staffId = object.id
    delete trainList.value[listIndex.value].id
  }
  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="培训计划编号:">
              <el-input
                v-model="formInline.logNo"
                :placeholder="pageType === 'detail' ? '无' : '系统自动生成 培训计划编号'"
                disabled
              />
            </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 label="计划编号:" prop="planId">
              <el-input
                v-model="formInline.planId"
                :placeholder="pageType === 'detail' ? '无' : '请选择计划编号'"
                :disabled="pageType === 'detail'"
              >
                <template #append>
                  <el-button
                    size="small"
                    :disabled="pageType === 'detail'"
                    @click="selectPlanId"
                  >
                    选择
                  </el-button>
                </template>
              </el-input>
            </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="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="培训效果:" 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" :disabled="pageType === 'detail'" placeholder="请输入或者选择" class="input">
              <template v-if="pageType !== 'detail'" #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 v-if="pageType !== 'detail'" #default="scope">
            <el-date-picker
              v-if="item.text === '签到时间'"
              v-model="scope.row[item.value]"
              type="datetime"
              :placeholder="`${item.text}`"
              format="YYYY/MM/DD HH:mm:ss"
              value-format="YYYY-MM-DD h:m:s"
              :disabled="pageType === 'detail'"
            />
            <el-input v-if="item.text !== '签到时间'" 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" />
  <!-- 选择培训数据组件 -->
  <plan-list-dialog ref="planListDialog" @add="confirmPlan" />
</template>

