<template>

  <div class="bigBox">
    <MOSTY.FromPage :title="props.title" @closeDialog="CloseEvent">
      <template #content>
        <MOSTY.Assort :title="'基本信息'" />
        <div class='Fromboxs'>
          <div class="qrcode" v-if="dialogForm.id">
            <MOSTY.ErwmImg :url="qrcodepxImg(dialogForm.id, 'aqxx', '', currDate)" :filename='"安全学习二维码"' />
          </div>
          <el-form :model="dialogForm" label-width="140px" :rules="rules" ref="ruleFormRef"
            :disabled="!props.saveBtnShow">
            <el-form-item label="所属单位:" style='width:45%;'>
              <el-input v-model="ssObj.dw" disabled style="width: 100%" />
            </el-form-item>
            <el-form-item label="所属部门:" style='width:45%;'>
              <el-input v-model="ssObj.bm" disabled style="width: 100%" />
            </el-form-item>
            <el-form-item label="安全主题:" prop="theme" style="width: 45%">
              <el-input v-model="dialogForm.theme" style="width: 100%" />
            </el-form-item>
            <el-form-item label="学习地点:" prop="address" style="width: 45%">
              <el-input v-model="dialogForm.address" style="width: 100%" />
            </el-form-item>
            <el-form-item label="学习日期:" prop="studyTime" style="width: 45%">
              <el-date-picker v-model="dialogForm.studyTime" style="width: 100%" type="date" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="学时:" prop="period" style='width:45%;'>
              <el-input v-model="dialogForm.period" type="number" clearable style="width: 100%">
                <template #append>学时</template></el-input>
            </el-form-item>
            <el-form-item label="学习类型:" prop="studyType" style="width: 100%">
              <MOSTY.Select placeholder="请选择学习类型" multiple :options="studyTypeOpt" v-model="dialogForm.studyType"
                selectType="select" :disabled="props.studyType ? true : false" />
            </el-form-item>
            <!-- 【驾驶员培训登记】 -->
            <el-form-item v-if="props.studyType" label="参与人员:" prop="username" style="width: 100%;display: flex;">
              <el-input v-model="dialogForm.username" maxlength="400" type="textarea" readonly show-word-limit autosize
                placeholder="不能超过400个字，人名以逗号隔开" style="width: 90.5%"></el-input>
              <el-button @click="ChooseJsy('01')" style="margin-left: 10px;">选择</el-button>

            </el-form-item>
            <!-- 【安全学习】 -->
            <el-form-item v-else label="参与人员:" prop="username" style="width: 100%;display: flex;">
              <el-input v-model="dialogForm.username" maxlength="400" type="textarea" readonly show-word-limit autosize
                placeholder="不能超过400个字，人名以逗号隔开" style="width: 90.5%"></el-input>
              <el-button @click="ChooesDdld('01')" style="margin-left: 10px;">选择</el-button>
            </el-form-item>
            <el-form-item label="学习内容:" style='width:100%;' prop="content">
              <el-input v-model="dialogForm.content" maxlength="500" :autosize="{ minRows: 2, maxRows: 5 }"
                type="textarea" show-word-limit placeholder="不能超过500个字" />
            </el-form-item>
            <el-form-item label="上传图片:" style="width: 100%">
              <MOSTY.Upload width="150px" :limit="3" :nopicer="false" :isImg="true" :ShowfileList="false"
                v-model="dialogForm.imgs" :disabled="!props.saveBtnShow">
              </MOSTY.Upload>
            </el-form-item>
            <el-form-item label="学习课件:" prop='files' style='width:100%;'>
              <MOSTY.Upload v-model="dialogForm.files" :isAutoWidth="true" :ShowfileList="true"
                :placeholder="'请上传pdf,ofd, doc, docx,wps'" :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'wps']"
                @filehandleChange="changeFile" :keys="key" :showinput="true" :limit="3" :nopicer="true"
                :isImg="false" />
            </el-form-item>
          </el-form>

        </div>
      </template>
      <template #footer>

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

    <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :data="memberList" :leaderid="leaderid"
      :deptId="props.orgcode" @choosedUsers="getSonValue"></ChooseUser>
    <!-- 选择人员 -->

    <!-- 驾驶员选择 -->
    <MOSTY.Choosejsy v-if="isShowJsy" v-model="isShowJsy" :Single="false" :leaderid="leaderid" @confirm="jsyChange"
      :empnature="undefined" :orgid="undefined" :defaultData="jsyData">
    </MOSTY.Choosejsy>
  </div>
</template>
<script setup>
// 引入
import { reactive, onMounted, ref, defineProps, watch, getCurrentInstance, computed } from "vue";
import { getApi, deleteApi, putApi, postApi } from "@/api/tobAcco_api.js";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import { ElMessage } from "element-plus";
import { getItem } from "@/utils/storage";
import * as rule from "@/utils/rules.js";
import * as MOSTY from "@/components/MyComponents/index";
const { proxy } = getCurrentInstance();
const { D_BZ_AQXX_TYPE } = proxy.$dict("D_BZ_AQXX_TYPE");
import { qrcodepxImg } from "@/utils/tools.js";
const emits = defineEmits(["close"]);

const props = defineProps({
  saveBtnShow: {
    default: true,
    type: Boolean
  },
  title: String,
  orgcode: String,
  rowId: {
    type: String,
    default: ''
  },
  /** 学习类型,有这个值代表是【驾驶员培训登记】，否则是【安全学习】  */
  studyType: {
    type: String,
    default: null
  }
});
// 数据
const chooseUserVisible = ref(false);
const singleShow = ref(false); //单选多选
const leaderid = ref("");
const memberList = ref([]);
const dialogForm = ref({});
const zzlx = ref(null);
const key = ref(0)
const currDate = ref(null);
const isShowJsy = ref(false) //是否显示驾驶员选择
/** 驾驶员回显数据格式[id,id] */
const jsyData = ref([]);
const ssObj = computed(() => {
  let _data = {
    bm: getItem("deptId").ssbmmc,
    dw: getItem("deptId").ssdwmc
  }
  return _data
})
/** 学习类型下拉 （安全学习没有驾驶员的下拉内容04） */
const studyTypeOpt = computed(() => {
  if (!D_BZ_AQXX_TYPE.value?.length) return []
  /** 是否安全学习 */
  const isAqxx = !props.studyType
  if (isAqxx) {
    return D_BZ_AQXX_TYPE.value.filter((item) => {
      return item.value != '04'
    });
  }
  return D_BZ_AQXX_TYPE.value
})
/** 学时验证 */
const periodValidator = (rule, value, callback) => {
  if (value > 0 && value <= 5 && isValidMaxTwoDecimal(value)) {
    callback();
  } else {
    callback(new Error('请输入0~5之间的值,小数点后最多两位。'));
  }
}
// 验证小数点后两位
function isValidMaxTwoDecimal(value) {
  const num = Number(value);
  if (isNaN(num)) {
    return false; // 非数字值返回false
  }
  // 将数值转换为字符串，并分割小数点前后的部分
  const [integerPart, decimalPart] = num.toString().split('.');
  if (!decimalPart) {
    return true; // 整数部分，没有小数部分，符合条件
  }
  // 小数部分长度不超过2位，符合条件
  return decimalPart.length <= 2;
}
const rules = reactive({
  username: [{ required: true, message: "请选择人员", trigger: "change" }],
  address: [{ required: true, message: "请输入学习地址", trigger: "blur" }],
  theme: [{ required: true, message: "请输入安全主题", trigger: "blur" }],
  studyTime: [{ required: true, message: "请选择学习日期", trigger: "change" }],
  period: [{ required: true, trigger: "blur", validator: periodValidator }],
  studyType: [{ required: true, message: "请选择学习类型", trigger: "blur" }],
  ryList: [{ required: true, message: "请选择参与人员", trigger: "change" }],
  content: [{ required: true, message: "请输入学习内容", trigger: "blur" }],
});
watch(
  () => props.rowId,
  (val) => {
    if (val) {
      getxqData(val)
    }

  },
  { deep: true, immediate: true }
);

const ruleFormRef = ref();
onMounted(() => {
  const now = new Date();
  currDate.value = now.getFullYear() + '-' + (now.getMonth() + 1) + '-' + now.getDate();
  if (props.studyType) {
    dialogForm.value.studyType = ['04']
  }
});

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

};
//获取详情
function getxqData(id) {
  getApi({ id }, `/mosty-jcgl/aqxx/getInfo`).then(
    (res) => {
      if (res) {
        dialogForm.value = res;
        dialogForm.value.username = ''
        res.ryList.map((item) => {
          dialogForm.value.username += item.username + ','
          memberList.value.push(item.userid)
        })
        dialogForm.value.username = dialogForm.value.username.slice(0, dialogForm.value.username.length - 1)
        if (dialogForm.value.studyType) dialogForm.value.studyType = dialogForm.value.studyType.split(',')
      }
    }
  );
}
// 新的文件上传返回
const changeFile = (row) => {
  key.value++
};
function ChooesDdld(val) {
  zzlx.value = val;
  if (val == "03" && dialogForm.value.username) {
    memberList.value = dialogForm.value.username.map((item) => {
      if (item.participantsid) return item.participantsid;
    });
  }
  chooseUserVisible.value = true;
  singleShow.value = false;
}
/** 展示驾驶员弹框 */
function ChooseJsy(val) {
  zzlx.value = val;
  isShowJsy.value = true;
  if (Array.isArray(dialogForm.value.ryList)) {
    jsyData.value = dialogForm.value.ryList.map((item) => {
      return item.userid;
    });
  }
}
/** 驾驶员选中 */
const jsyChange = (value) => {
  const arr = value.map(item => ({
    username: item.userName,
    userid: item.id,
    // userid: item.driveruserid,
    ssdwid: item.nameaffiliationid,
    // nameaffiliationid: item.nameaffiliationid
  }));

  dialogForm.value.username = value.map(item => item.userName).join(',');
  dialogForm.value.ryList = arr;
};
const getSonValue = (value) => {
  let arr = [];
  let arrStr = []
  for (let i = 0; i < value.length; i++) {
    const element = value[i];
    element.zzlx = zzlx.value;
    arr.push({ username: element.userName, userid: element.id });
    arrStr.push(element.userName);
  }
  memberList.value = value.map((item) => {
    return item.id;
  });

  dialogForm.value.username = arrStr.toString();
  dialogForm.value.ryList = arr;
};

// 接收外层新增保存
const loading = ref(false); //新增保存按钮截流
const save = async (ruleFormRef) => {
  if (!ruleFormRef) return;
  await ruleFormRef.validate((valid) => {
    if (valid) {
      loading.value = true;
      const params = {
        ...dialogForm.value,
        files: dialogForm.value.files ? dialogForm.value.files.toString() : "",
        imgs: dialogForm.value.imgs ? dialogForm.value.imgs.toString() : "",
        studyType: dialogForm.value.studyType ? dialogForm.value.studyType.toString() : "",
      }
      if (props.rowId) {
        postApi(params, "/mosty-jcgl/aqxx/editOneAqxx")
          .then(() => {
            ElMessage.success("修改成功");
            emits("close");
          }).finally(() => {
            loading.value = false;
          })
      } else {
        postApi(params, "/mosty-jcgl/aqxx/addOneAqxx")
          .then(() => {
            ElMessage.success("新增成功");
            emits("close");
          }).finally(() => {
            loading.value = false;
          })
      }
    } else {
      ElMessage.error("请输入正确和必填的值!");
    }
  });
};
</script>

<style lang="scss" scoped>
::v-deep .el-form-item__content {
  flex-wrap: nowrap !important;
}

::v-deep .el-form--inline .el-form-item {
  display: inline-flex !important;
  vertical-align: middle !important;
  margin-right: 32px;
}

::v-deep .el-form-item {
  margin: 9px !important;
}

.Fromboxs {
  display: flex;
  justify-content: start;
}

.bigBox {
  display: block !important;
}

.el-form {
  width: 1000px;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin: 0 auto;
}

.qrcode {
  margin-left: 30px;
  // width: 300px;
  // margin: auto;

  // >img {
  //   width: 100%;
  //   height: 100%;
  // }
}
</style>
