<template>
  <div class="bigBox">
    <MOSTY.FromPage :title="props.addobj.title" @closeDialog="handleClose">
      <template #content>
        <el-form class="mosty-from-wrap" ref="ruleFormRef" label-width="134px" :model="ruleForm" :inline="true"
          :rules="rules" :disabled="!props.addobj.savebtnshow">
          <el-form-item label="培训项目：" prop="planName">
            <el-input v-model="ruleForm.planName" style="width: 337px" maxlength="100" autosize type="textarea"
              show-word-limit placeholder="不能超过100个字"></el-input>
          </el-form-item>
          <el-form-item label="主办部门：" prop="planHostsDeptName">
            <el-input v-model="ruleForm.planHostsDeptName" disabled clearable style="width: 337px"></el-input>
          </el-form-item>
          <el-form-item label="培训对象：" prop="planTraineeType">
            <div style="width: 337px;">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_PXDX" v-model="ruleForm.planTraineeType" selectType="select"
                :disabled="!props.addobj.savebtnshow" :multiple='true' :placeholder="'请选择培训对象'" />
            </div>
          </el-form-item>
          <el-form-item label="项目负责人：" prop="planChargePersonName">
            <el-input v-model="ruleForm.planChargePersonName" readonly clearable style="width: 337px">
              <template #append>
                <el-button class='cursor' @click="ChooesDdld('02')">选择</el-button></template>
            </el-input>
          </el-form-item>
          <el-form-item label="培训渠道：" prop="planChannel">
            <div style="width: 337px;">
              <MOSTY.DictRidioAndSelect :dictData="D_TB_PXQD" v-model="ruleForm.planChannel" selectType="select"
                :disabled="!props.addobj.savebtnshow" :placeholder="'请选择培训渠道'" />
            </div>
          </el-form-item>
          <el-form-item label="师资渠道：" prop="planTeachersChannel">
            <div style="width: 337px;">
              <MOSTY.DictRidioAndSelect :dictData="D_TB_SZQD" v-model="ruleForm.planTeachersChannel" selectType="select"
                :disabled="!props.addobj.savebtnshow" :placeholder="'请选择师资渠道'" />
            </div>
          </el-form-item>
          <el-form-item label="预算费用：" prop="planBudget">
            <el-input v-model="ruleForm.planBudget" type="Number" maxlength="6" @input="check" style="width: 337px">
              <template #append>元</template>
            </el-input>
          </el-form-item>
          <el-form-item label="培训人数：" prop="planTraineeNumber">
            <el-input v-model="ruleForm.planTraineeNumber" type="Number" maxlength="4" @input="check1"
              style="width: 337px">
              <template #append>人</template>
            </el-input>
          </el-form-item>
          <el-form-item label="课时：" prop="planClassHour">
            <el-input v-model="ruleForm.planClassHour" type="Number" maxlength="4" @input="check2" style="width: 337px">
              <template #append>小时</template>
            </el-input>
          </el-form-item>
          <el-form-item label="举办时间（月）：" prop="planImplementationDate">
            <el-date-picker v-model="ruleForm.planImplementationDate" type="month" format="YYYY-MM"
              value-format="YYYY-MM" style="width: 337px" :disabled-date="disablednowmonth">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="培训地点：" prop="place">
            <el-input v-model="ruleForm.place" clearable style="width: 337px"></el-input>
          </el-form-item>
          <el-form-item label="培训内容：" prop="planContent" style='width:100%;'>
            <el-input v-model="ruleForm.planContent" maxlength="500" :autosize="{ minRows: 2, maxRows: 5 }"
              type="textarea" style='width:100%;' show-word-limit placeholder="不能超过500个字" />
          </el-form-item>
          <el-form-item label="上传附件：" style='width:100%;'>
            <MOSTY.Upload v-model="ruleForm.pxjhfj" :delrow="delrow" isAutoWidth :widthNumber="1316" :isEdit="fileEdit"
              :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'xls', 'xlsx', 'wps']" :ShowfileList="true"
              @filehandleChange="changeFile" :showinput="true" :limit="1" :nopicer="true" :isImg="false" />
          </el-form-item>
        </el-form>
      </template>
      <template #footer>

        <el-button type="primary" :loading="loading" v-if="props.addobj.savebtnshow" @click="handleSave(ruleFormRef)">
          <el-icon>
            <DocumentChecked />
          </el-icon>
          <span>保存</span>
        </el-button>
        <el-button @click="handleClose" type="primary">
          <el-icon>
            <DocumentDelete />
          </el-icon>
          <span>关闭</span>
        </el-button>

      </template>
      <template #dwbox>
        <!-- 选择部门 -->
        <Choosebm v-if="showDept" :showDdld="showDept" @closezzjg="closezzjg" @listdata="getSonValue" :zzlx="zzlx" />
        <!-- 选择人员 -->
        <!-- 选择带队领导 -->
        <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :data="memberList" :leaderid="leaderid"
          searchType="01" @choosedUsers="getSonValue"></ChooseUser>
        <!-- 选择计划实施部门 -->
        <ChooseDept :showDdld="showJkssbm" @closezzjg="closeJhss" @listdata="getSonValue" :zzlx="zzlx" />
      </template>
    </MOSTY.FromPage>
  </div>
</template>

<script setup>
// 引入
import {
  ref,
  onMounted,
  defineProps,
  defineEmits,
  reactive,
  watch,
  getCurrentInstance,
  nextTick,
  onUnmounted,
} from "vue";
import { getItem } from "@/utils/storage";
import * as MOSTY from "@/components/MyComponents/index";
import { useRouter } from "vue-router";
import { getApi, postApi, putApi } from "@/api/tobAcco_api.js";
import ChooseDept from "@/components/MyComponents/ChooseDept/Depart.vue";
import Choosebm from "@/components/MyComponents/ChooseDept/index.vue";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import { ElMessage } from "element-plus";
import * as rule from "@/utils/rules.js";
import { disablednowmonth, isString } from "@/utils/tools.js";
const { proxy } = getCurrentInstance();
const { D_TB_JCLX, D_BZ_PXDX, D_TB_PXQD, D_TB_SZQD } = proxy.$dict(
  "D_TB_JCLX",
  "D_BZ_PXDX",
  "D_TB_PXQD",
  "D_TB_SZQD"
);
const deptId = ref('')
const loading = ref(false); //新增保存按钮截流
// 数据
const zzlx = ref(null);
const showDept = ref(false); //选择部门
const chooseUserVisible = ref(false); //选择人员
const showJkssbm = ref(false); //选择人员
const singleShow = ref(true); //单选多选
const leaderid = ref("");
/** 上传附件宽度 */
const uploadWidth = ref(700);
//表单数据
const ruleForm = ref({
  planHostsDeptName: getItem('deptId').ssbmmc,
  planHostsDeptId: getItem('deptId').ssbmid
});

//规则校验
const rules = reactive({
  planName: [{ required: true, message: "培训项目不能为空", trigger: "blur" }],
  ...rule.intfsRule({ validator: true, require: false }, "planBudget"),
  ...rule.intRule({ validator: true, require: false }, "planTraineeNumber"),
  ...rule.intRule({ validator: true, require: true }, "planClassHour"),
  planHostsDeptName: [
    { required: true, message: "主办部门不能为空", trigger: "blur" }
  ],
  planTraineeType: [
    { trigger: "blur", required: true, message: "培训对象不能为空" }
  ],
  planChannel: [
    { trigger: "blur", required: true, message: "培训渠道不能为空" }
  ],
  planTeachersChannel: [
    { trigger: "blur", required: true, message: "师资渠道不能为空" }
  ],
  planChargePersonName: [
    { trigger: "blur", required: true, message: "项目负责人不能为空" }
  ],
  planImplementationDate: [
    { trigger: "blur", required: true, message: "举办时间不能为空" }
  ],
  place: [
    { trigger: "blur", required: true, message: "培训地点不能为空" }
  ],
  planContent: [{ trigger: "blur", required: true, message: "培训内容不能为空" }]
});
const props = defineProps({
  addobj: Object
});
const emits = defineEmits(["changeAddVi", "changeclose"]);
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 1000,
  tname: ""
});
/** 设置”上传“组件宽度 */
const setWidth = () => {
}
onMounted(() => {
  if (props.addobj.id) {
    getxqData(props.addobj.id);
  } else {
    ruleForm.value = {};
    ruleForm.value.planHostsDeptName = getItem('deptId').ssbmmc,
      ruleForm.value.planHostsDeptId = getItem('deptId').ssbmid
  }
  setWidth();
  window.addEventListener('resize', setWidth);
});
onUnmounted(() => {
  window.removeEventListener('resize', setWidth);
});
//获取详情
function getxqData(id) {
  getApi({ id: id }, "/mosty-jcgl/training/getInfoJh").then((res) => {
    ruleForm.value = res;
    ruleForm.value.planTraineeType = ruleForm.value.planTraineeType.split(",");
  });
}
function check(event) {
  if (ruleForm.value.planBudget.length > 6) {
    ruleForm.value.planBudget = ruleForm.value.planBudget.slice(0, 6);
  }
}
function check1(event) {
  if (ruleForm.value.planTraineeNumber.length > 4) {
    ruleForm.value.planTraineeNumber = ruleForm.value.planTraineeNumber.slice(0, 4);
  }
}
function check2(event) {
  if (ruleForm.value.planClassHour.length > 4) {
    ruleForm.value.planClassHour = ruleForm.value.planClassHour.slice(0, 4);
  }
}

function ChooesDdld(val) {
  zzlx.value = val;
  //选择检查成员
  if (val == "02") {
    deptId.value = getItem("deptId").ssbmid
    singleShow.value = true;
    chooseUserVisible.value = true;
    leaderid.value = ruleForm.value.planChargePersonId;
  } else if (val == "03") {
    showJkssbm.value = true;
  } else {
    showDept.value = true;
  }
}
const getSonValue = (value) => {
  if (zzlx.value == "01") {
    ruleForm.value.planHostsDeptName = value.orgName;
    ruleForm.value.planHostsDeptId = value.id;
  } else if (zzlx.value == "02") {
    ruleForm.value.planChargePersonName = value[0].userName;
    ruleForm.value.planChargePersonId = value[0].id;
    // ruleForm.value.xmfzrOrgcode = value.id;
  } else if (zzlx.value == "03") {
    let arr = [];
    for (let i = 0; i < value.length; i++) {
      const element = value[i];
      arr.push(element.orgName);
    }
    ruleForm.value.jhssbmList = value.map((item) => {
      return {
        userId: item.orgCode,
        userName: item.orgName
      };
    });
    ruleForm.value.jhssbm = arr.join(",");
  }
};
//关闭弹窗
const closezzjg = (val) => {
  showDept.value = val;
};
const closeJhss = (val) => {
  showJkssbm.value = val;
};
const ruleFormRef = ref();
// 保存
const handleSave = async (ruleFormRef) => {
  if (!ruleFormRef) return;
  await ruleFormRef.validate((valid) => {
    if (valid) {
      if (ruleForm.value) {
        loading.value = true;
        ruleForm.value.planTraineeType = ruleForm.value.planTraineeType ? ruleForm.value.planTraineeType.toString() : null;
        ruleForm.value.pxjhfj = ruleForm.value.pxjhfj ? ruleForm.value.pxjhfj.toString() : null;
        if (props.addobj.id) {
          postApi(ruleForm.value, "/mosty-jcgl/training/edit")
            .then((res) => {
              loading.value = false;
              ElMessage.success("修改成功");
              emits("changeAddVi", false);
            }).finally(() => {
              loading.value = false;
              ruleForm.value.planTraineeType = ruleForm.value.planTraineeType && isString(ruleForm.value.planTraineeType) ? ruleForm.value.planTraineeType.split(',') : ruleForm.value.planTraineeType;
            })
        } else {
          postApi(ruleForm.value, "/mosty-jcgl/training/add")
            .then((res) => {
              loading.value = false;
              ElMessage.success("新增成功");
              emits("changeAddVi", false);
            }).catch((err) => {
              loading.value = false;
              ruleForm.value.planTraineeType = ruleForm.value.planTraineeType && isString(ruleForm.value.planTraineeType) ? ruleForm.value.planTraineeType.split(',') : ruleForm.value.planTraineeType;
            })

        }
      }
    } else {
      ElMessage.error("请输入必填项");
    }
  });
};

// 关闭
const handleClose = () => {
  if (props.addobj.savebtnshow) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        // 关闭上一次的表单校验
        ruleFormRef.value.clearValidate();
        ruleForm.value = {}
        emits("changeAddVi", false);
      })
      .catch(() => {
        // catch error
      })
  } else {
    // 关闭上一次的表单校验
    ruleFormRef.value.clearValidate();
    ruleForm.value = {}
    emits("changeAddVi", false);
  }

};

// 关闭×
const closeDialog = () => {
  loading.value = false;
  emits("changeAddVi", false);
  emits("changeclose", false);
};
</script>

<style lang="scss" scoped>
.fj {
  .el-form {
    padding: 10px;
    margin-top: 10px;
    flex-wrap: wrap;
    // width: 1170px;
    justify-content: flex-end;
  }

  .from_fix {
    display: flex;
    flex-wrap: wrap;
    padding: 10px;
    margin-top: 10px;

    // .el-form-item--default .el-form-item__content {
    //   flex-wrap: nowrap !important;
    // }

    .el-input {
      width: 100%;
    }
  }
}

::v-deep .el-form-item__content {
  flex-wrap: nowrap !important;
}

.el-form {
  padding: 10px 67px;
  // width: 1650px;
  margin: 10px auto;
  flex-wrap: wrap;
  justify-content: start;
}

.el-form-item {
  text-align: center;
}

.pxdx_box {
  width: 500px;
}

.titleBox {
  align-items: center;
  margin: 0;
  padding: 0;
  height: 60px;
  border: 1px solid rgb(32, 75, 54);
  padding: 20px;
}



.three {
  justify-content: flex-start !important;

  .el-select {
    width: 15%;
  }
}

.four {
  display: flex;
  align-items: center;

  span {
    width: 5%;
  }

  .el-textarea__inner {
    width: 95%;
  }
}

.group {
  margin-top: 50px;
  // background-color: red;
  position: relative;
}

.fj {
  margin-top: 50px;
  width: 100%;

  .content {
    width: 100%;
    display: flex;
    padding: 20px;

    div {
      display: flex;
      width: 85%;
      align-items: center;
    }

    justify-content: space-between;
  }
}

.jc {
  margin-top: 50px;
}

.tabBox {
  height: 300px !important;
}

.el-table {
  height: 300px !important;
  border: 1px solid var(--el-color-primary);
}

.el-form-item__content {
  flex-wrap: nowrap;
}

.el-collapse {
  border-color: var(--el-color-primary);
  height: 460px;
}

::v-deep .el-collapse-item__header {
  border-bottom-color: var(--el-color-primary);
  color: #000 !important;
}

::v-deep .el-collapse-item__header.is-active {
  border-bottom-color: transparent;
}

::v-deep .el-textarea.is-disabled .el-textarea__inner {
  color: #000 !important;
}

::v-deep .el-select .select-trigger .el-select__tags {
  text-align: left !important;
}
</style>
