<template>
  <div>
    <el-dialog :title="props.title" width="1200px" v-model="props.addDiaShow" :before-close="handleClose">
      <div class="config">
        <el-form :model="ruleForm" :rules="rules" label-width="135px" class="demo-ruleForm.value" :disabled="disableds">
          <el-form-item label="培训计划:" prop="planName">
            <el-input v-model="ruleForm.planName" maxlength="100" autosize type="textarea" show-word-limit
              placeholder="不能超过100个字" style="width: 1100px"></el-input>
          </el-form-item>
          <el-form-item label="主办部门：" prop="planHostsDeptName">
            <el-input v-model="ruleForm.planHostsDeptName" clearable style="width: 500px"></el-input>
          </el-form-item>
          <el-form-item label="培训渠道：">
            <el-select v-model="ruleForm.planChannel" clearable placeholder="请选择培训渠道">
              <el-option v-for="item in D_TB_PXQD" :key="item" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="培训类型：" prop="otherType">
            <el-select v-model="ruleForm.otherType" clearable>
              <el-option v-for="item in GZ_TRAINOT" :key="item" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="培训地点:" prop="place">
            <el-input v-model="ruleForm.place" maxlength="100" type="textarea" show-word-limit placeholder="不能超过100个字"
              style="width: 500px"></el-input>
          </el-form-item>
          <el-form-item label="业务类型：">
            <el-select v-model="ruleForm.specialityType" clearable placeholder="请选择业务类型：">
              <el-option v-for="item in D_TB_YWLX" :key="item" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="培训开始日期：" prop="startDate">
            <el-date-picker v-model="ruleForm.startDate" style="width: 100%" type="date" placeholder="培训开始日期"
              format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="培训结束日期：" prop="finshDate">
            <el-date-picker v-model="ruleForm.finshDate" style="width: 100%" type="date" placeholder="培训结束日期"
              format="YYYY/MM/DD" value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="报道截止时间：" prop="signFinshDate">
            <el-date-picker v-model="ruleForm.signFinshDate" style="width: 100%" type="date" format="YYYY/MM/DD"
              value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="项目负责人：" prop="planChargePersonName">
            <el-input v-model="ruleForm.planChargePersonName" clearable style="width: 100%"
              :disabled="disableds"></el-input>
            <el-button style="margin-left: 10px" @click="ChooesDdld('02')">选择</el-button>
          </el-form-item>
          <el-form-item label="联系人：" prop="contactorName">
            <el-input v-model="ruleForm.contactorName" clearable style="width: 100%"></el-input>
          </el-form-item>
          <el-form-item label="联系人电话：" prop="contactorPhone">
            <el-input v-model="ruleForm.contactorPhone" type="Number" clearable style="width: 100%"></el-input>
          </el-form-item>
          <el-form-item label="培训总人数：" prop="implementationTraineeNumber">
            <el-input v-model="ruleForm.implementationTraineeNumber" clearable style="width: 100%"></el-input>
          </el-form-item>
          <el-form-item label="培训预算（元）：" prop="realBudget">
            <el-input v-model="ruleForm.realBudget" type="Number" maxlength="7" @input="check"
              style="width: 100%"></el-input>
          </el-form-item>
          <el-form-item label="考核方式：" prop="examinationType">
            <el-select v-model="ruleForm.examinationType" clearable>
              <el-option v-for="item in D_TB_PXKHFS" :key="item" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>

          <el-form-item label="培训课时：" prop="realClassHour">
            <el-input v-model="ruleForm.realClassHour" type="Number" maxlength="3" @input="check1"
              style="width: 100%"></el-input>
          </el-form-item>
          <el-form-item label="学员是否评价：">
            <el-select v-model="ruleForm.planChannel" clearable>
              <el-option v-for="item in ispjlist" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="培训教师：" prop="teachers">
            <el-input v-model="ruleForm.teachers" maxlength="200" type="textarea" show-word-limit
              placeholder="不能超过200个字" style="width: 1100px"></el-input>
          </el-form-item>
          <el-form-item label="培训内容:">
            <el-input v-model="ruleForm.realContent" maxlength="500" type="textarea" show-word-limit
              placeholder="不能超过500个字" style="width: 1100px" />
          </el-form-item>
          <el-form-item label="备注:">
            <el-input v-model="ruleForm.bz" maxlength="500" type="textarea" show-word-limit placeholder="不能超过500个字"
              style="width: 1100px" />
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-collapse v-model="activeNames">
          <el-collapse-item title="培训人员列表" name="1">
            <div>
              <div class="addbtn">
                <el-button type="primary" @click="ChooesDdld('03')">
                  <el-icon>
                    <CirclePlus />
                  </el-icon>
                  <span>添加</span>
                </el-button>
              </div>
              <div>
                <el-table ref="multipleTableRef" :data="ruleForm.signList" stripe style="width: 100%"
                  @selection-change="handleSelectionChange" border>
                  <el-table-column label="学员名称" property="name"></el-table-column>
                  <el-table-column label="所属部门名称" property="deptName"></el-table-column>
                  <el-table-column label="操作" width="250">
                    <template #default="scope">
                      <span class="operate" style="color: yellowgreen" @click="deldetexy(scope.row)">删除</span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" :loading="loading" @click="handleSave">
            <el-icon>
              <DocumentChecked />
            </el-icon>
            <span>保存</span>
          </el-button>
          <el-button @click="handleClose" type="primary">
            <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span>
          </el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 选择主办部门名称: -->
    <Choosebm :formInfo="fromObj" :showDdld="showDept" @closezzjg="closezzjg" @listdata="getSonValue" :zzlx="zzlx" />
    <!-- 选择负责人 :deptId="listQuery.orgCode" -->
    <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :data="memberList" :leaderid="leaderid"
      @choosedUsers="getSonValue"></ChooseUser>
    <!-- 选择参加单位汇总: -->
    <ChooseDept v-if="showCjdw" :formInfo="fromObj" :showDdld="showCjdw" @closezzjg="closedept" @listdata="getSonValue"
      :zzlx="zzlx" />
    <!-- 选择考试试卷 -->
    <AddTest v-model="showJkssbm" :Single="true" :formInfo="fromObj" @closezzjg="closeJhss" @listdata="getSonValue"
      :data="taskList" :zzlx="zzlx" />
  </div>
</template>

<script setup>
// 引入
import {
  ref,
  onMounted,
  defineProps,
  defineEmits,
  reactive,
  watch,
  getCurrentInstance
} from "vue";
import { getApi, postApi, putApi } from "@/api/tobAcco_api.js";
import { qrcodeImg, createAndClickLink } from "@/utils/tools.js";
import { ElMessage } from "element-plus";
import * as rule from "@/utils/rules.js";
import * as MOSTY from "@/components/MyComponents/index";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import Choosebm from "@/components/MyComponents/ChooseDept/index.vue";
import ChooseDept from "@/components/MyComponents/ChooseDept/Depart.vue";
import AddTest from "./addTest.vue";
const { proxy } = getCurrentInstance();
const { D_TB_YWLX, D_TB_PXKHFS, D_TB_PXQD, GZ_TRAINOT } = proxy.$dict(
  "D_TB_YWLX",
  "D_TB_PXKHFS",
  "D_TB_PXQD",
  "GZ_TRAINOT"
);
const loading = ref(false); //新增保存按钮截流
// 数据
const zzlx = ref(null);
const leaderid = ref("");
const singleShow = ref(true); //单选多选
const chooseUserVisible = ref(false); //选择负责人弹窗
const memberList = ref([]); //成员选择的id回显
const taskList = ref([]);
const uploadList = ref([]); //上传文件列表
const uploadimgs = ref([]); //上传图片列表
const fjtableData = ref([]); //新增文件表格数据
const delrow = ref({}); //删除文件列表
const delrows = ref({}); //删除文件列表
const activeNames = ref(1);
const total = ref(0);
const showDept = ref(false); //选择部门
const showPeop = ref(false); //选择人员
const showJkssbm = ref(false); //选择试卷
const showCjdw = ref(false); //选择参选部门
const showcxxy = ref(false); //选择参训学员
const showlable = ref(false); //是否显示对应参数
const disableds = ref(false); //是否显示对应参数
const ispjlist = ref([
  { value: "1", label: "是" },
  { value: "0", label: "否" }
]);
const imgurl = ref("");
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 10
});
const prames = ref({});
//表单数据
const ruleForm = ref({
  signList: []
});
const tableData = ref([]); //表格数据
//规则校验
const rules = reactive({
  planName: [
    { required: true, message: "培训计划选择不能为空", trigger: "blur" }
  ],
  planHostsDeptName: [
    { required: true, message: "主办部门不能为空", trigger: "blur" }
  ],
  planChargePersonName: [
    { trigger: "blur", required: true, message: "项目负责人不能为空" }
  ],
  place: [{ trigger: "blur", required: true, message: "培训地点不能为空" }],
  startDate: [
    { trigger: "blur", required: true, message: "培训开始日期不能为空" }
  ],
  finshDate: [
    { trigger: "blur", required: true, message: "培训结束日期不能为空" }
  ],
  signFinshDate: [
    { trigger: "blur", required: true, message: "报道截止时间不能为空" }
  ],
  contactorName: [
    { trigger: "blur", required: true, message: "联系人不能为空" }
  ],
  ...rule.phoneRule({ validator: true, require: true }, "contactorPhone"),
  implementationTraineeNumber: [
    { trigger: "blur", required: true, message: "培训总人数不能为空" }
  ],
  realBudget: [
    { trigger: "blur", required: true, message: "培训预算不能为空" }
  ],
  examinationType: [
    { trigger: "blur", required: true, message: "考核方式不能为空" }
  ],
  otherType: [{ trigger: "blur", required: true, message: "培训类型不能为空" }],
  realClassHour: [
    { trigger: "blur", required: true, message: "培训课时不能为空" }
  ]
});

const emits = defineEmits(["changeAddVi", "changeclose"]);

const props = defineProps({
  addDiaShow: {
    type: Boolean,
    default: false
  },
  title: String,
  xqId: String,
  type: String
});

watch(
  () => props.title,
  (val) => {
    showlable.value = false;
  },
  { deep: true, immediate: true }
);
watch(
  () => props.xqId,
  (val) => {
    getJhssxq(val);
  }
);

onMounted(() => { });

//计划内实施-详情
function getJhssxq(id) {
  getApi({ id: id }, "/mosty-jcgl/training/pxssInfoJhn").then((res) => {
    ruleForm.value = res;
    if (res.files) {
      uploadList.value = res.files.split(",");
    }
  });
}
function check(event) {
  if (ruleForm.value.realBudget.length > 7) {
    ruleForm.value.realBudget = ruleForm.value.realBudget.slice(0, 7);
  }
}
function check1(event) {
  if (ruleForm.value.realClassHour.length > 3) {
    ruleForm.value.realClassHour = ruleForm.value.realClassHour.slice(0, 3);
  }
}

//选择人员或部门
function ChooesDdld(value) {
  zzlx.value = value;
  leaderid.value = "";
  //主办部门
  if (value == "01") {
    showDept.value = true;
  }
  //项目负责人
  if (value == "02") {
    singleShow.value = true;
    chooseUserVisible.value = true;
    leaderid.value = ruleForm.value.planChargePersonId;
  }
  //人员多选
  if (value == "03") {
    singleShow.value = false;
    chooseUserVisible.value = true;
    if (ruleForm.value.signList) {
      memberList.value = ruleForm.value.signList.map((item) => {
        return item.userId;
      });
    }
  }
  //考试题多选
  if (value == "04") {
    showJkssbm.value = true;
    if (ruleForm.value.libraryList) {
      taskList.value = ruleForm.value.libraryList.map((item) => {
        return item.id;
      });
    }
  }
  //选择参选部门
  if (value == "05") {
    showCjdw.value = true;
  }
}
//编辑部门
const handledeptChange = (val) => {
  if (val) {
    ruleForm.value.deptList.forEach((item) => {
      if (item.orgCode == val.orgCode) {
        item.isbj = true;
      } else {
        item.isbj = false;
      }
    });
  }
};
//删除部门
const deldetedept = (row) => {
  if (row) {
    ruleForm.value.deptList = ruleForm.value.deptList.filter((item) => {
      return item.orgCode != row.orgCode;
    });
  }
};
//获取部门、人员
const getSonValue = (value) => {
  if (zzlx.value == "01") {
    ruleForm.value.planHostsDeptName = value.orgName;
    ruleForm.value.planHostsDeptId = value.id;
  }
  if (zzlx.value == "02") {
    ruleForm.value.planChargePersonName = value[0].userName;
    ruleForm.value.planChargePersonId = value[0].id;
  }
  if (zzlx.value == "03") {
    ruleForm.value.signList = value;
    ruleForm.value.signList.forEach((item) => {
      item.name = item.userName;
      item.phone = item.telePhone;
      item.userId = item.id;
    });
    memberList.value = value.map((item) => {
      return item.id;
    });
  }
  if (zzlx.value == "04") {
    ruleForm.value.libraryList = value;
  }
  if (zzlx.value == "05") {
    ruleForm.value.deptList = value.map((item) => {
      return {
        orgCode: item.orgCode,
        orgName: item.orgName,
        traineeDistributionNum: 0,
        bz: "",
        ifbj: false
      };
    });
  }

  //   sonMessage.value = value
};
//删除考试题
function deldetetest(val) {
  for (let i = 0; i < ruleForm.value.libraryList.length; i++) {
    const el = ruleForm.value.libraryList[i];
    if (el.id == val.id) {
      ruleForm.value.libraryList.splice(i, 1);
    }
  }
}
//删除人员列表选择
function deldetexy(val) {
  for (let i = 0; i < ruleForm.value.signList.length; i++) {
    const el = ruleForm.value.signList[i];
    if (el.id == val.id) {
      ruleForm.value.signList.splice(i, 1);
    }
  }
}
//关闭弹窗
const closezzjg = (val) => {
  showDept.value = val;
};
const closedept = (val) => {
  showCjdw.value = val;
};

// 新的文件上传返回
const changeFile = (data) => {
  fjtableData.value = data;
  if (fjtableData.value) {
    ruleForm.value.files = fjtableData.value
      .map((it) => {
        if (it.response) return it.response.data;
      })
      .toString();
  }
};
//新的图片返回
const changeImg = (data) => {
  if (data) {
    ruleForm.value.imgs = data.map((it) => {
      if (it.response) return it.response.data;
    });
  }
};
//删除文件
const handlefjdelete = (row) => {
  delrow.value = row;
  fjtableData.value = fjtableData.value.filter((item) => {
    return item != row;
  });
};
//点击下载文件
function handledlon(val) {
  createAndClickLink(val.url, val.name)
}

const closeJhss = (val) => {
  showJkssbm.value = val;
};
//清空数据
function reset() {
  fjtableData.value = [];
  ruleForm.value = {};
  uploadList.value = [];
  uploadimgs.value = [];
}
function postgetdata(data, url, text) {
  postApi(data, url)
    .then((res) => {
      ElMessage.success(text);
      reset();
      emits("changeAddVi", false);
    })
    .catch((err) => {
      ElMessage.warning(err);
    });
}
// 保存
const handleSave = () => {
  if (ruleForm.value) {
    ruleForm.value.imgs = ruleForm.value.imgs
      ? ruleForm.value.imgs.toString()
      : "";
    ruleForm.value.realClassHour = parseInt(ruleForm.value.realClassHour);
    ruleForm.value.realBudget = parseFloat(ruleForm.value.realBudget);
    ruleForm.value.implementationTraineeNumber = parseInt(
      ruleForm.value.implementationTraineeNumber
    );
    if (ruleForm.value.deptList) {
      ruleForm.value.deptList.forEach((it) => {
        it.traineeDistributionNum = parseInt(it.traineeDistributionNum);
      });
    }
    if (props.title == "计划外培训实施") {
      postgetdata(
        ruleForm.value,
        "/mosty-jcgl/training/pxssAddJhw",
        "新增成功"
      );
    }
    if (props.title == "培训计划修改") {
      postgetdata(
        ruleForm.value,
        "/mosty-jcgl/training/pxssEditJhw",
        "修改成功"
      );
    }
  }
};

// 关闭
const handleClose = () => {
  proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
    .then(() => {
      reset();
      emits("changeAddVi", false);
    })
    .catch(() => {
      // catch error
    })

};

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

<style lang="scss" scoped>
.sele-title {
  display: flex;
  justify-content: space-between;
  font-size: 16px;
  padding: 10px 20px;
}

.sele-titles {
  display: flex;
  justify-content: space-between;
  font-size: 16px;
  padding: 10px 20px 0px 50px;

  // >span {
  //     display: block;
  //     width: 33%;
  //     text-align: center;
  // }
}

.beiz {
  width: 100%;
  padding: 10px;
  background: #0b6047;
}

.addbtn {
  margin: 10px;
}

.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;
}

.config {
  .el-form {
    padding: 10px 40px;
    margin-top: 10px;
    flex-wrap: wrap;
    justify-content: space-between;
  }

  .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;
}

.form>div {
  position: relative;
  margin-top: 30px;
  display: flex;
  justify-content: space-between;

  div {
    display: flex;
    align-items: center;

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

.el-input {
  width: 75%;
}

.two .el-input {
  width: 65%;
}

.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);
}

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

.erweim {
  width: 17%;
  margin: 0px auto;
  text-align: center;

  >img {
    width: 200px;
    height: 200px;
    display: block;
  }
}
</style>
