<template>
  <div class="bigBox">
    <MOSTY.FromPage :title="props.title" @closeDialog="CloseEvent">
      <template #content>
        <MOSTY.Assort :title="'基本信息'" />
        <div class='FromBoxs'>
          <el-form :model="dialogForm" label-width="140px" :rules="rules" ref="ruleFormRef"
            :disabled="!props.saveBtnShow">
            <el-form-item label="荣誉名称：" prop="titlename" style='width:100%;'>
              <el-input v-model="dialogForm.titlename" maxlength="50" autosize type="textarea" show-word-limit
                placeholder="不能超过50个字" />
            </el-form-item>
            <el-form-item label="颁发单位：" prop="fbjg" style="width: 45%">
              <el-input v-model="dialogForm.fbjg" style="width: 100%" />
            </el-form-item>
            <el-form-item label="获奖时间：" prop="time" style="width: 45%">
              <el-date-picker v-model="dialogForm.time" style="width: 100%" type="date" format="YYYY-MM-DD"
                value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="获奖等级：" prop="level" style="width: 45%">
              <MOSTY.Select v-model="dialogForm.level" filterable style="width: 100%;" :options="D_BZ_LWJB">
                <!-- <el-option v-for="item in D_BZ_LWJB" :key="item.value" :label="item.label" :value="item.value" /> -->
              </MOSTY.Select>
            </el-form-item>
            <el-form-item label="是否公开：" prop="sfgk" style="width: 45%" v-if='orgLevel == "1"'>
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_SF" v-model="dialogForm.sfgk" selectType="radio"
                :disabled="false" style="width: 100%;" />
            </el-form-item>
            <el-form-item label="年份：" prop="year" style="width: 45%">
              <el-date-picker v-model="dialogForm.year" style="width: 100%" type="year" format="YYYY"
                value-format="YYYY" />
            </el-form-item>
            <el-form-item label="获奖对象：" prop="honorType" style="width: 45%">
              <MOSTY.DictRidioAndSelect :dictData="D_BZ_HJDX" v-model="dialogForm.honorType" selectType="radio"
                :disabled="false" style="width: 100%;" />
            </el-form-item>
            <el-form-item label="获奖人：" prop="username" style="width: 100%" v-if="dialogForm.honorType == '2'">
              <el-input v-model="dialogForm.username" readonly autosize type="textarea">
              </el-input>
              <el-button style='margin-left:10px;' @click="ChooesDdld('01')">选择</el-button>
            </el-form-item>
            <el-form-item label="获奖单位：" prop="honorOrgname" style="width: 100%" v-if="dialogForm.honorType == '1'">
              <el-input v-model="dialogForm.honorOrgname" readonly autosize type="textarea">
              </el-input>
              <el-button style='margin-left:10px;' @click="ChooesDdld('02')">选择</el-button>
            </el-form-item>
            <el-form-item label="备注：" style='width:100%;'>
              <el-input v-model="dialogForm.bz" maxlength="500" type="textarea" autosize show-word-limit
                placeholder="不能超过500个字" />
            </el-form-item>
            <el-form-item label="附件：" prop='files' style='width:100%;'>
              <MOSTY.Upload v-model="dialogForm.files" :delrow="delrow" :widthNumber="665" :isEdit="fileEdit"
                :placeholder="'请上传pdf,ofd, doc, docx,wps'" :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'wps']"
                :ShowfileList="true" @filehandleChange="changeFile" :showinput="true" :limit="4" :nopicer="true"
                :isImg="false" />
            </el-form-item>
            <el-form-item label="图片:" style='width:100% !important;'>
              <MOSTY.Upload :width="'100%'" :limit="5" :nopicer="false" :isImg="true" :ShowfileList="false"
                v-model="dialogForm.imgs" :nameshow='true' :gsgfList="['jpg', 'png', 'jpeg', 'gif']">
              </MOSTY.Upload>
            </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>
    <ChooseDept :data="taskList" :showDdld="showJkssbm" :searchType="'01'" @closezzjg="closeJhss" :Isstrictly='true'
      @listdata="getSonValue" :zzlx="zzlx" />
    <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :leaderid="leaderid" :deptId="props.orgcode"
      :data="memberList" :xtbmry='true' @choosedUsers="getSonValue"></ChooseUser>
  </div>
</template>
<script setup>
// 引入
import { reactive, onMounted, ref, defineProps, watch, getCurrentInstance } from "vue";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import ChooseDept from "@/components/MyComponents/ChooseDept/Departnobj.vue";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import { ElMessage } from "element-plus";
import * as MOSTY from "@/components/MyComponents/index";
const { proxy } = getCurrentInstance();
const { D_BZ_SF, D_BZ_HJDX, D_BZ_LWJB } = proxy.$dict("D_BZ_SF", "D_BZ_HJDX", "D_BZ_LWJB");
const emits = defineEmits(["close"]);
const memberList = ref([]); //成员选择的id回显
const orgLevel = ref(JSON.parse(
  window.localStorage.getItem("deptId")
).orgLevel.substring(0, 1))
const taskList = ref([])
const props = defineProps({
  saveBtnShow: {
    default: true,
    type: Boolean
  },
  title: String,
  orgcode: String,
  rowId: String
});
// 数据
const chooseUserVisible = ref(false);
const singleShow = ref(true); //单选多选
const leaderid = ref("");
const dialogForm = ref({});
const fileEdit = ref(true);
const zzlx = ref(null);
const rules = reactive({
  titlename: [{ required: true, message: "请输入荣誉名称", trigger: "change" }],
  fbjg: [{ required: true, message: "请输入颁发单位", trigger: "change" }],
  username: [{ required: true, message: "请选择获奖人", trigger: "change" }],
  honorOrgname: [{ required: true, message: "请选择单位", trigger: "change" }],
  year: [{ required: true, message: "请选择年份", trigger: "change" }],
  honorType: [{ required: true, message: "请选择获奖对象", trigger: "change" }],
  time: [{ required: true, message: "请选择获奖时间", trigger: "change" }],
  sfgk: [{ required: true, message: "请选择是否公开", trigger: "change" }],
  level: [{ required: true, message: "请选择获奖等级", trigger: "change" }],
  files: [{ required: true, message: "请选择附件", trigger: "change" }]
});
const showJkssbm = ref(false);
watch(
  () => props.rowId,
  (val) => {

    if (val) {
      getxqData(val)
    }

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

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

};
const closeJhss = () => {
  showJkssbm.value = false
}
//获取详情
function getxqData(id) {
  getApi({ id }, `/mosty-jcgl/safetypaperCommend/getDetailById`).then(
    (res) => {
      if (res) {
        dialogForm.value = res;
      }
    }
  );
}
// 新的文件上传返回
const changeFile = (row) => { };
function ChooesDdld(val) {
  zzlx.value = val;
  memberList.value = []
  if (val == "01") {
    memberList.value = dialogForm.value.userid ? dialogForm.value.userid.split(',') : [];
    chooseUserVisible.value = true;
    singleShow.value = false;
  } else {
    taskList.value = dialogForm.value.honorOrgcode ? dialogForm.value.honorOrgcode.split(',') : []
    showJkssbm.value = true
  }

}
const getSonValue = (value) => {
  if (zzlx.value == '01') {
    let arr = [];
    let arrid = [];
    for (let i = 0; i < value.length; i++) {
      const element = value[i];
      element.zzlx = zzlx.value;
      arr.push(element.userName);
      arrid.push(element.id);
    }
    memberList.value = value.map((item) => {
      return item.id;
    });
    dialogForm.value.username = arr.toString();
    dialogForm.value.userid = arrid.toString();
  } else {
    let userarr = [];
    for (let i = 0; i < value.length; i++) {
      const element = value[i];
      userarr.push(element.orgName);
    }
    dialogForm.value.honorOrgcode = value.map((item) => {
      return item.id;
    }).toString();
    dialogForm.value.honorOrgname = userarr.toString();
    showJkssbm.value = false
  }

};
// 接收外层新增保存
const loading = ref(false); //新增保存按钮截流
const save = async (ruleFormRef) => {
  if (!ruleFormRef) return;
  await ruleFormRef.validate((valid) => {
    if (valid) {
      loading.value = true;
      // dialogForm.value.year = new Date().getFullYear();
      dialogForm.value.type = '2';
      dialogForm.value.files = dialogForm.value.files ? dialogForm.value.files.toString() : "";
      dialogForm.value.imgs = dialogForm.value.imgs ? dialogForm.value.imgs.toString() : "";
      if (dialogForm.value.id) {
        postApi(dialogForm.value, "/mosty-jcgl/safetypaperCommend/edit")
          .then((res) => {
            loading.value = false;
            ElMessage.success("修改成功");
            emits("close");
          }).catch((err) => {
            loading.value = false;
          })

      } else {
        postApi(dialogForm.value, "/mosty-jcgl/safetypaperCommend/add")
          .then((res) => {
            loading.value = false;
            ElMessage.success("新增成功");
            emits("close");
          }).catch((err) => {
            loading.value = false;
          })
      }
    } else {
      ElMessage.error("请输入必填项!");
    }
  });
};
onMounted(()=>{
  const isAdd = !dialogForm.value?.id
  if(isAdd){
    dialogForm.value.year = new Date().getFullYear().toString()
  }
})
</script>

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


.bigBox {
  display: block !important;


}

.el-form {
  width: 800px;
  align-items: center;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
  margin: 0 auto;

}
</style>
