<script lang="ts" setup name="listPageAdd">
import type { FormInstance } from 'element-plus'
import { ElMessageBox } from 'element-plus'
import { pa } from 'element-plus/es/locale'
import ManageBox from './manageBox.vue'
import {
  getDeptTree,
  getListAdd,
  getListDetail,
  getListLogupdate,
} from '@/api/system/plan'

const loading = ref(false) // 表单加载状态
const infoId = ref('') // id
const buttonArray = ref<string[]>([])
const pageType = ref('detail') // 页面类型: add,edit, detail
const buttonLoading = ref(false) // 按钮加载状态
const textMap: { [key: string]: string } = {
  edit: '编辑',
  detail: '详情',
}// 字典
// 从路由中获取页面类型参数
const $route = useRoute()
if ($route.params && $route.params.type) {
  pageType.value = $route.params.type as string
  if (pageType.value === 'detail') {
    buttonArray.value = ['同意', '驳回', '拒绝']
  }
  else if (pageType.value === 'edit') {
    buttonArray.value = ['提交']
  }
  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 options = ref([])
const ruleFormRef = ref<FormInstance>()
const columns = [
  { text: '学员名称', value: 'name' },
  { text: '单位名称', value: 'company' },
  { text: '技术职称', value: 'technologyJob' },
  { text: '签到时间', value: 'signTime', type: '下拉' },
]
const dialogVisible = ref(false)
// 校验规则
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' }],
  deptName: [{ required: true, message: '主管部门不能为空', trigger: 'blur' }],
  effectiveCompany: [{ required: true, message: '实施单位不能为空', trigger: 'blur' }],
  director: [{ required: true, message: '负责人不能为空', trigger: 'blur' }],
  trainContent: [{ required: true, message: '培训内容不能为空', trigger: 'blur' }],
}) // 表单验证规则
const addPersonList = ref({
  company: '',
  examResult: '',
  id: 0,
  name: '',
  remark: '',
  signTime: '',
  staffId: 0,
  technologyJob: '',
})
const SelectionList = ref([])
// 控制审批操作弹窗的开关
const applyShow = ref(false)
// 获取到组织信息
const getDept = () => {
  const params = {
    roleId: '',
    deptType: '',
    tips: '',
  }
  getDeptTree(params).then((response) => {
    options.value = response.data
  })
}
getDept()
// 初始化router
const $router = useRouter()
// 关闭新增页面的回调
const close = () => {
  $router.back()
}
const addRoow = () => {
  Object.keys(addPersonList.value).forEach(
    key => (addPersonList.value[key] = ''),
  )
  dialogVisible.value = true
}
// 点击关闭
const handleVisibleClose = () => {
  dialogVisible.value = false
}
// 点击弹窗的完成追加到表格数组中
const addPushList = () => {
  formInline.value.trainStaffList.push(
    JSON.parse(JSON.stringify(addPersonList.value)),
  )
  handleVisibleClose()
}
// 删除行
const deleteList = () => {
  formInline.value.trainStaffList = formInline.value.trainStaffList.filter(
    (item) => {
      return !SelectionList.value.includes(item)
    },
  )
}
const handleSelectionChange = (e: any) => {
  SelectionList.value = e
}
if (infoId.value && infoId.value !== '') {
  getListDetail({ id: infoId.value }).then((res) => {
    formInline.value = res.data
  })
}
const getAddList = async (formEl: FormInstance | undefined, buttonType: string) => {
  console.log(formInline.value)
  if (buttonType === '提交' && pageType.value !== 'edit') {
    if (!formEl) { return }
    await formEl.validate((valid, fields) => {
      if (valid) {
        ElMessageBox.confirm(
    `确认${buttonType}吗？`,
    '提示',
    {
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      type: 'warning',
    },
        ).then(() => {
          getListAdd(formInline.value).then((res) => {
            if (res.code === 200) {
              close()
            }
          })
        })
      }
    })
  }
  else {
    applyShow.value = true
  }
}
// 审批弹窗关闭
const handleClose = () => {
  applyShow.value = false
}
// 点击审批的提交
const applyListSubmit = (row: any) => {
  console.log(row)
  handleClose()
}
</script>

<template>
  <app-container>
    <detail-page :title="`培训计划审批-${textMap[pageType]}`">
      <template #btns>
        <el-button v-for="(item, index) in buttonArray" :key="index" type="primary" @click="getAddList(ruleFormRef, item)">
          {{ item }}
        </el-button>
        <el-button v-if=" pageType === 'edit'" type="primary">
          保存
        </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="deptName">
              <el-select
                v-model="formInline.deptName"
                clearable
                placeholder="主管部门"
                size="default"
                :disabled="pageType === 'detail'"
              >
                <el-option
                  v-for="item in options"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </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'"
              />
            </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="buttonType !== '详情'" type="info" @click="deleteList">
          删除行
        </el-button>
        <el-button v-if="buttonType !== '详情'" 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="handleVisibleClose"
    center
  >
    <el-form
      ref="addPersonListForm"
      label-position="left"
      label-width="100px"
      :model="addPersonList"
      style="max-width: 460px;"
    >
      <el-form-item label="学员名称">
        <el-input v-model="addPersonList.name" />
      </el-form-item>
      <el-form-item label="单位名称">
        <el-input v-model="addPersonList.company" />
      </el-form-item>
      <el-form-item label="技术职称">
        <el-input v-model="addPersonList.technologyJob" />
      </el-form-item>
      <el-form-item label="签到时间">
        <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>
    <el-button type="primary" class="dialog-button" @click="addPushList">
      完成
    </el-button>
  </el-dialog>
  <manage-box :apply-show="applyShow" @applyListSubmit="applyListSubmit" @handleClose="handleClose" />
</template>

<style lang="scss" scoped>
.top-info {
  width: 100%;
  height: 50px;
  padding-right: 10px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-radius: 10px;
  background-color: #fff;

  .title {
    width: 75%;
    text-align: center;
  }
}

.info-content {
  margin-top: 10px;
  padding: 30px;
  border-radius: 10px;
  background-color: #fff;

  .info-dizhi {
    margin-right: 155px;
  }
}

.input-width .el-input {
  width: 30vw;
}

.table-top {
  margin-top: 10px;
  padding: 5px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 10px;
  background-color: #fff;

  .table-top-title {
    width: 60vw;
    text-align: center;
  }
}

.dialog-button {
  margin-left: 50%;
  transform: translateX(-50%);
}
</style>
