<script lang="ts" setup name="planlogAdd">
import type { FormInstance } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { IObject, ITrinLogFormInline } from './plan_interface'
import userListDialog from './components/userListDialog.vue'
import PlanListDialog from './components/planListDialog.vue'
import useUserStore from '@/store/modules/user'
import {
  getListDetail,
  getListLogAdd,
  getListLogDetail,
  getListLogupdate,
} from '@/api/measure/plan'

const infoId = ref('') // id
const pageType = ref('add') // 页面类型: add,edit, detail
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()
// 数据校验ref
const ruleFormRef = ref<FormInstance>()
// 培训记录新增数据
const formInline = ref<ITrinLogFormInline>({
  improveMethod: '', // 改进措施
  logNo: '', // 记录编号
  preparer: name || '', // 人员
  problems: '', // 存在问题
  planId: '', // 培训id
  planNo: '', // 培训计划编号
  remark: '', // 备注
  id: '', // 主键id
  trainAddress: '', // 培训地点
  trainContent: '', // 培训内容
  trainEffect: '', // 培训效果
  trainHour: '', // 培训学时
  trainName: '', // 培训名称
  trainNumber: '', // 培训人数
  trainPerson: '', // 培训对象
  trainStaffList: [], // 培训人员列表
  trainTime: '', // 培训时间
})

const trainList = ref<IObject[]>([]) // 人员信息列表数据
// 表头
const columns = ref([
  { text: '学员名称', value: 'name', required: true },
  { text: '单位名称', value: 'company', required: true },
  { text: '技术职称', value: 'technologyJob', required: true },
  { text: '签到时间', value: 'signTime', width: '180', required: false },
  { text: '考核结果', value: 'examResult', required: true },
])
// 校验规则
const rules = ref({
  logNo: [{ required: true, message: '编号必填', trigger: ['blur', 'change'] }],
  preparer: [{ required: true, message: '填表人必填', trigger: ['blur', 'change'] }],
  planNo: [{ 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'] },
    { pattern: /(^[1-9]\d*$)/, 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 SelectionList = ref<IObject[]>([])
const ListDetail = ref([]) // 选择完培训计划编号带出来的人员信息

// 初始化router
const $router = useRouter()
// 关闭新增页面的回调
const close = () => {
  $router.back()
}
// 新增行
const addRow = () => {
  if (formInline.value.planId === '') {
    return ElMessage.warning('请先选择培训名称')
  }
  const index = trainList.value.findIndex(item => !item.name)
  if (index !== -1) {
    return ElMessage.warning('请完善上一行数据')
  }
  const tempData = {
    company: '', // 单位名称
    examResult: '', // 考核结果
    name: '', // 学员名称
    remark: '', // 备注
    signTime: '', // 签到时间
    technologyJob: '', // 技术职称
    planId: '', // 培训id
    staffId: '', // 任务id
  }
  trainList.value.push(tempData)
}

// 删除行
const deleteList = () => {
  trainList.value = trainList.value.filter(
    (item: IObject) => {
      return !SelectionList.value.includes(item)
    },
  )
  console.log(trainList.value)
}
// 下拉框
const handleSelectionChange = (e: any) => {
  SelectionList.value = e
}

// 只要有id就会获取详情
if (infoId.value && infoId.value !== '') {
  getListLogDetail({ id: infoId.value }).then((res) => {
    formInline.value = res.data
    trainList.value = formInline.value.trainStaffList
  })
}
// 点击删除和编辑的参数类型
interface rowReturn {
  id: string
  planNo: string
  planName: string
}

// 保存
const getAddList = async (formEl: FormInstance | undefined, buttonType: string) => {
  // 检查考核结果
  const index = trainList.value.findIndex(item => !item.examResult)
  if (index !== -1) {
    ElMessage.warning(`请填写表格第${index + 1}行考核结果`)
    return
  }
  if (!formEl) { return }
  await formEl.validate((valid, fields) => {
    if (valid) {
      ElMessageBox.confirm(
    `确认${buttonType}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
      ).then(() => {
        if (buttonType === '保存' && pageType.value === 'add') { // 新建
          formInline.value.trainStaffList = trainList.value
          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: IObject) => {
            delete item.updateTime
            delete item.createTime
          })
          formInline.value.id = infoId.value
          getListLogupdate(formInline.value).then((res) => {
            if (res.code === 200) {
              ElMessage.success('提交成功')
              close()
            }
          })
        }
      })
    }
  })
}

// 打印
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) => {
    console.log(res)

    ListDetail.value = res.data.trainStaffList
    trainList.value = res.data.trainStaffList // 人员信息列表--自动填写表格
    // formInline.value.trainStaffList = res.data.trainStaffList
    res.data.preparer = name
    formInline.value = { ...res.data }
    formInline.value.planNo = data.planNo // 培训编号
    formInline.value.planId = data.id // 培训计划表id
    formInline.value.trainName = data.planName // 培训名称
  })
}
// 选择完人员信息
const confirmPerson = (object: IObject) => {
  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('该学员已经存在')
  }
}
</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="planNo">
              <el-input
                v-model="formInline.planNo"
                :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
              >
                <template v-if="pageType !== 'detail'" #append>
                  <el-button
                    size="small"
                    @click="selectPlanId"
                  >
                    选择
                  </el-button>
                </template>
              </el-input>
            </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
              />
            </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
              />
            </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
              />
            </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 HH:mm:ss"
                disabled
              />
            </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
              />
            </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
              />
            </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
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </detail-page>
    <detail-block title="人员信息">
      <!-- <template #btns>
        <el-button v-if="pageType === 'add'" type="primary" :disabled="pageType === 'detail'" @click="addRow">
          增加行
        </el-button>
        <el-button v-if="pageType === 'add'" type="info" :disabled="pageType === 'detail'" @click="deleteList">
          删除行
        </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" :width="item.width" 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-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 HH:mm:ss"
              :disabled="pageType === 'detail'"
            /> -->
            <!-- <el-input v-if="item.text === '考核结果' && pageType !== 'detail'" v-model="scope.row[item.value]" :placeholder="`${item.text}`" class="input" /> -->

            <el-select
              v-if="item.text === '考核结果' && (pageType === 'edit' || pageType === 'add')"
              v-model="scope.row.examResult"
              placeholder="请选择考核结果"
            >
              <el-option v-for="item of ['优秀', '良好', '及格', '不及格']" :key="item" :label="item" :value="item" />
            </el-select>
            <span v-else>{{ scope.row[item.value] }}</span>
          </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>

