<template>
  <div>
    <MOSTY.FromPage :title="props.editObj.title" @closeDialog="black">
      <template #content>
        <MOSTY.Assort :title="'基本信息'" />
        <div class="box">
          <div style="display: flex; justify-content: center; margin-top: 10px;width: 100%;">
            <el-form ref="ruleFormRef" :model="data.formData" :rules="rules" label-width="120px" class="demo-ruleForm"
              status-icon :inline="true" style="display: inline-block;" label-suffix="："
              :disabled="!props.editObj.saveBtnShow">
              <el-row>
                <el-col :span="12">
                  <el-form-item label="项目名称" prop="name">
                    <el-input v-model="data.formData.name" placeholder="请输入项目名称" style="width: 250px"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="培训地点" prop="trainingLocation">
                    <el-input v-model="data.formData.trainingLocation" placeholder="请输入培训地点"
                      style="width: 250px"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="培训类别" prop="type">
                    <el-select v-model="data.formData.type" placeholder="请选择岗位类别" style="width: 250px">
                      <el-option v-for="item in D_TB_ZDPXLX" :key="item.value" :label="item.label"
                        :value="item.value" />
                    </el-select>
                  </el-form-item>
                </el-col>

                <el-col :span="12">
                  <el-form-item label="培训学时" prop="totalHour">
                    <el-input v-model.number="data.formData.totalHour" type='number' placeholder="请输入培训学时"
                      style="width: 250px">
                      <template #append>小时</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="开始时间" prop="startTime">
                    <el-date-picker v-model="data.formData.startTime" style="width: 250px" type="date"
                      placeholder="开始日期" format="YYYY-MM-DD" value-format="YYYY-MM-DD" :disabled-date="disablednowDates"
                      @change='changetime' />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="结束时间" prop="endTime">
                    <el-date-picker v-model="data.formData.endTime" type="date" placeholder="选择结束时间"
                      style="width: 250px" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                      :disabled-date="disablednowDate2" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="主办部门名称" prop="deptName">
                    <el-input v-model="data.formData.deptName" style="width: 250px" readonly>
                      <template #append>
                        <el-button class='cursor' @click="selectDept">选择</el-button></template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="培训人员" prop="trainingUser">
                    <el-input v-model="data.formData.trainingUser" style="width: 250px" readonly
                      @click.stop="selectUser('培训人员')">
                      <template #append>
                        <el-button class='cursor' @click.stop="selectUser('培训人员')">选择</el-button></template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="负责人" prop="userName">
                    <el-input v-model="data.formData.userName" style="width: 250px" readonly
                      @click.stop="selectUser('负责人')">
                      <template #append>
                        <el-button class='cursor' @click.stop="selectUser('负责人')">选择</el-button></template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="联系人:" prop="contacts">
                    <el-input v-model="data.formData.contacts" clearable style="width: 250px"
                      placeholder="请输入联系人"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="联系电话:" prop="contactNumber">
                    <el-input v-model="data.formData.contactNumber" type="number" clearable style="width: 250px"
                      placeholder="请输入联系电话"></el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="培训预算" prop="trainingBudget">
                    <el-input v-model.number="data.formData.trainingBudget" type='number' placeholder="请输入培训预算"
                      style="width: 250px">
                      <template #append>元</template>
                    </el-input>
                  </el-form-item>
                </el-col>
                <el-col :span="24">
                  <el-form-item label="培训图片" prop="trainingPicture">
                    <MOSTY.Upload :width="'100%'" :limit="5" :nopicer="false" :isImg="true" :ShowfileList="true"
                      :disabled="!props.editObj.saveBtnShow" v-model="data.formData.trainingPicture" :nameshow='true'
                      :gsgfList="['jpg', 'png']">
                    </MOSTY.Upload>
                  </el-form-item>
                </el-col>

              </el-row>
            </el-form>
          </div>
        </div>
      </template>
      <template #footer>

        <el-button type="primary" v-loading='loadingshow' v-if="props.editObj.saveBtnShow" @click="submit(ruleFormRef)">
          <el-icon>
            <DocumentChecked />
          </el-icon>保存
        </el-button>
        <el-button @click="black">
          <el-icon>
            <DocumentDelete />
          </el-icon>关闭</el-button>
      </template>
    </MOSTY.FromPage>


    <!-- 选择人员 -->
    <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :data="memberList" @choosedUsers="getSonValue">
    </ChooseUser>
    <!-- 选择部门 -->
    <Choosebm :formInfo="fromObj" :showDdld="showDept" @closezzjg="closezzjg" @listdata="getDeptValue" :zzlx="zzlx" />
  </div>
</template>
<script setup>
import { reactive, ref, watchEffect, getCurrentInstance, } from "vue";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";

import * as MOSTY from "@/components/MyComponents/index";
import PageTitle from "@/components/PageTitle/PageTitle.vue";
import { ElMessage } from "element-plus";
import { postApi } from "@/api/tobAcco_api.js";
import { filterYear } from "@/utils/auth.js";
import * as rule from "@/utils/rules.js";
import { disablednowDates } from "@/utils/tools.js";
import Choosebm from "@/components/MyComponents/ChooseDept/index.vue";

const { proxy } = getCurrentInstance();
const { D_TB_ZDPXLX, } = proxy.$dict("D_TB_ZDPXLX");
const props = defineProps({
  editObj: {
    type: Object,
    default: () => { },
  }
});
const fromObj = ref([])
const zzlx = ref()
const loadingshow = ref(false)
const showDept = ref(false); //选择部门
const emit = defineEmits("changePage");
const ruleFormRef = ref();
/** 当前选择人员的表单名称  */
const currChooseUserName = ref('')
const data = reactive({
  formData: {
    id: '',
    userId: '', // 用户id
    userName: '', // 用户姓名
    deptId: '',
    deptName: '', // 部门名称
    orgId: '', // 单位id
    orgName: '', // 单位名称
    type: '', // 岗位类别
    year: new Date().getFullYear(), // 年份
    mainHeadTeachingQty: '', // 授课次数
    neAnnualTotalHour: '', // 年度总学时
    // bz: '', // 备注
  }
});
data.formData.type
// 车辆选择框展示
const showCar = ref(false)
/** 选择人员组件显示 */
const chooseUserVisible = ref(false)
const singleShow = ref(false)
const memberList = ref([])

const yearOpt = ref(filterYear(5))
const rules = {
  deptName: [{ required: true, message: "请选择部门", trigger: "change" }],
  userName: [{ required: true, message: "请选择人员", trigger: "change" }],
  ...rule.intRule({ validator: true, require: true }, "mainHeadTeachingQty"),
  ...rule.intRule({ validator: true, require: true }, "neAnnualTotalHour"),
};
const getMemberList = (title) => {
  if (title == '培训人员') {
    if (!data.formData.trainingUserIds) return []
    return typeof data.formData.trainingUserIds == 'string' ? data.formData.trainingUserIds.split(',') : []
  } else if (title == '负责人') {
    return data.formData.userId ? [data.formData.userId] : []
  }
}
/** 选择人员
 * @param {string} title 选择人员的表单名称 ['培训人员', '负责人']
 */
const selectUser = (title) => {
  currChooseUserName.value = title
  singleShow.value = title == '负责人' ? true : false
  memberList.value = getMemberList(title)

  chooseUserVisible.value = true
}
/** 保存人员数据 */
const getSonValue = (value) => {
  const users = Array.isArray(value) ? value : []
  if (currChooseUserName.value == '培训人员') {
    data.formData.trainingUser = users.map(item => item.userName).join(',')
    data.formData.trainingUserIds = users.map(item => item.id).join(',')
  } else {
    data.formData.userName = users[0].userName
    data.formData.userId = users[0].id
    // data.formData.orgId = users[0].orgId
    // data.formData.orgName = users[0].orgName
  }
}
const selectDept = () => {
  showDept.value = true
}
/** 保存部门数据 */
const getDeptValue = (value) => {
  data.formData.deptName = value.orgName
  data.formData.deptId = value.id
}
//关闭弹窗
const closezzjg = (val) => {
  showDept.value = val;
};
const changetime = () => {
  data.formData.endTime = ''
}
// 结束时间
function disablednowDate2(time) {
  if (!data.formData.startTime) return false
  return time.getTime() < new Date(data.formData.startTime).getTime()
}
// 保存
const submit = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      loadingshow.value = true
      if (Array.isArray(data.formData.trainingPicture)) {
        data.formData.trainingPicture = data.formData.trainingPicture?.join(',')
      }
      if (!data.formData.id) {
        postApi(data.formData, "/mosty-jcgl/training/staffTrainingInfo/saveStaffTrainingInfo")
          .then(() => {
            ElMessage.success("新增成功");
            black()
            loadingshow.value = false
          })
      } else {
        postApi(data.formData, "/mosty-jcgl/training/staffTrainingInfo/editStaffTrainingInfo")
          .then(() => {
            ElMessage.success("修改成功");
            loadingshow.value = false
            black()
          })
      }
    } else {
      ElMessage.error("请输入必填项!");
    }
  });
};

const black = () => {
  let obj = {
    ...props.editObj
  };
  emit("changePage", "Main", obj);
};

watchEffect(() => {
  if (props.editObj) {
    data.formData = props.editObj;
    // if(data.formData.trainingUserIds){
    //   data.formData.trainingUserIds = data.formData.trainingUserIds.split(',')
    // }
  }
});
</script>
<style lang="scss" scoped>
.box {

  width: 800px;
  color: black;
  font-size: 20px;
  margin: 0 auto;
}
</style>