<template>
  <!-- <div class="bigBox" :style="{ height: bigHeight }"> -->
  <div class="bigBox">
    <MOSTY.FromPage :title="props.title" @closeDialog="CloseEvent">
      <template #content>
        <MOSTY.Assort :title="'基本信息'" />
        <div style="width: 100%;height: 77vh; overflow-y: scroll;">
          <el-form ref="ruleFormRef" :model="data.addForm" :rules="rules" :disabled="!props.saveBtnShow"
            label-width="150px" status-icon :inline="true">
            <el-form-item label="年度:" prop="year">
              <el-input style="width: 400px;" v-model="data.addForm.year" disabled>
                <template #append>年</template>
              </el-input>
            </el-form-item>
            <el-form-item label="参会日期:" prop="time">
              <el-date-picker v-model="data.addForm.time" type="date" value-format="YYYY-MM-DD" style="width: 400px"
                placeholder="请选择参会日期" @change="timeChange" />
            </el-form-item>
            <el-form-item label="上/下半年:" prop="quarter">
              <el-select v-model="data.addForm.quarter" clearable placeholder="请选择上/下半年" style="width: 400px"
                :disabled="isEdit" @change="retrievalTimes">
                <el-option label="上半年" value='1' />
                <el-option label="下半年" value='2' />
              </el-select>
              <!-- <MOSTY.DictRidioAndSelect style="width:400px" selectType="select" :dictData="D_BZ_JDCS" :disabled="isEdit"
                placeholder="请选择上/下半年" v-model="data.addForm.quarter" /> -->
            </el-form-item>
            <el-form-item v-if="isFirstAdd" label="会议次数:" prop="frequency">
              <el-select v-model="data.addForm.frequency" clearable placeholder="请选择会议次数" style="width: 400px"
                :disabled="isEdit">
                <el-option v-if="data.addForm.frequencyNum" :label="`第${data.addForm.frequencyNum || 'XX'}次会议`"
                  :value="data.addForm.frequencyNum" />
                <el-option v-else :label="`-`" :value="''" />
              </el-select>
            </el-form-item>
            <el-form-item v-else label="会议次数:" prop="frequency">
              <el-input style="width: 400px;" v-model="frequencyDisplay" disabled />
            </el-form-item>
            <el-form-item label="会议名称:" prop="meetingname">
              <el-input v-model="data.addForm.meetingname" autocomplete="off" style="width:400px" />
            </el-form-item>
            <el-form-item label="会议地点:">
              <el-input v-model="data.addForm.address" autocomplete="off" style="width:400px" />
            </el-form-item>
            <el-form-item label="参会人员:" prop="username" style=" width: 80%;overflow-x: scroll;">
              <el-input v-model="data.addForm.username" type="textarea" autosize readonly
                style="width:90%;margin-right:5px;"></el-input>
              <el-button type="primary" @click="ChooesDdld('01')">选择</el-button>
            </el-form-item>
            <el-form-item label="签到表:" style="width: 80%;">
              <MOSTY.Upload v-model="data.addForm.signin" :isAutoWidth="true" :showinput="true" :limit="1"
                :showbut="true" :nopicer="true" :isEdit="fileEdit" @filehandleChange="changeFile1" :ShowfileList="true"
                :isImg="false" />
            </el-form-item>
            <el-form-item label="会议纪要/记录:" style="width: 80%">
              <MOSTY.Upload v-model="data.addForm.files" :isAutoWidth="true" :nopicer="true" :showinput="true"
                :limit="1" :showbut="true" :isEdit="fileEdit" @filehandleChange="changeFile" :ShowfileList="true"
                :isImg="false" :placeholder="'请上传pdf,ofd, doc, docx,mp3,wps'"
                :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'mp3', 'wps']" />
            </el-form-item>
            <el-form-item label="会议资料:" prop="otherFiles" style="width: 80%">
              <MOSTY.Upload v-model="data.addForm.otherFiles" :isAutoWidth="true" :nopicer="true" :showinput="true"
                :limit="10" :showbut="true" :isEdit="fileEdit" @filehandleChange="changeFile2" :ShowfileList="true"
                :isImg="false" :placeholder="'请上传pdf,ofd, doc, docx,wps'"
                :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'wps']" />
            </el-form-item>
            <el-form-item label="会议图片:" style="width: 100%">
              <MOSTY.Upload :width="'917'" :limit="3" :nopicer="false" :isImg="true" :ShowfileList="false"
                v-model="data.addForm.pics" :nameshow='true' :gsgfList="['jpg', 'png']" :disabled="!props.saveBtnShow">
              </MOSTY.Upload>
            </el-form-item>
            <el-form-item label="备注:" style="width: 80%;overflow-x: scroll;">
              <el-input v-model="data.addForm.bz" type="textarea" autosize autocomplete="off" style="width:90%" />
            </el-form-item>
          </el-form>
          <div v-if="props.type === 'view'">
            <Detail :id="rowId"></Detail>
          </div>
        </div>
      </template>
      <template #footer>

        <el-button style="margin-left: 10px" type="primary" v-if="props.saveBtnShow" :loading="loading"
          @click="searchHander(ruleFormRef)">
          <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>
  </div>
</template>

<script setup>
import { onMounted, ref, defineEmits, reactive, getCurrentInstance, computed } from "vue";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import Detail from "../issueWorkTasks/components/Detail.vue"
import { filterYear } from "@/utils/auth.js";
import { ElMessage } from "element-plus";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, postApi } from "@/api/tobAcco_api.js";
const { proxy } = getCurrentInstance();
const { D_BZ_JDCS } = proxy.$dict("D_BZ_JDCS");
import * as rule from "@/utils/rules.js";
import { useRoute } from "vue-router";
const route = useRoute();
const emits = defineEmits(["close"]);
const chooseUserVisible = ref(false);
const ruleFormRef = ref();
const leaderid = ref(null);
const filename = ref("");
const hyjyname = ref("");
const hyjyname2 = ref("");
const singleShow = ref(true); //单选多选
const fileEdit = ref(true);
const zzlx = ref(null);
const props = defineProps({
  saveBtnShow: {
    default: true,
    type: Boolean
  },
  agencyData: Object,
  // 安委会数据
  title: String,
  rowId: String,
  orgcode: String,
  isEdit: false,
  taskId: {
    type: String,
  },
  frequencyNum: {
    type: Number,
  },
  isFirstAdd: {
    default: false,
    type: Boolean
  },
  type: {
    type: String,
    default: "add"
  }
});
const data = reactive({
  addForm: {
    type: "2",
    year: new Date().getFullYear()
  }
});
const memberList = ref([]); //成员选择的id回显
//规则校验
const rules = reactive({
  year: [{ required: true, message: "年度不能为空", trigger: "blur" }],
  time: [{ required: true, message: "参会日期不能为空", trigger: "blur" }],
  quarter: [{ required: true, message: "上/下半年不能为空", trigger: "blur" }],
  frequency: [{ required: true, message: "会议次数不能为空", trigger: "blur" }],
  meetingname: [{ required: true, message: "会议名称不能为空", trigger: "blur" }],
  files: [{ required: true, message: "会议纪要不能为空", trigger: "blur" }],
  signin: [{ required: true, message: "签到表不能为空", trigger: "blur" }],
  username: [{ required: true, message: "参会人员不能为空", trigger: "blur" }]
});
const listQuery = reactive({});
const loading = ref(false); //新增保存按钮截流
// 初始化
onMounted(() => {
  if (props.type === "add") {
    props.taskId = null
  }
  if (!props.isFirstAdd) {
    data.addForm.frequency = props.frequencyNum;
    data.addForm.frequencyNum = props.frequencyNum;
  }
  if (props.rowId) {
    xqData(props.rowId)
  } else {
    data.addForm.userid = `${props.agencyData.officemembersid},${props.agencyData.pscexecutivedeputyid},${props.agencyData.pscchairmanid}`
    // data.addForm.username = `${props.agencyData.officemembers},${props.agencyData.pscexecutivedeputy}(常务副主任),${props.agencyData.pscchairman}(主任)`
  }
  // if (route.path === '/dutyBook/jgryandzz/index') {
  // typeNum='1'
  // }else if(route.path === '/dutyBook/jgryandzz/index') {
  // typeNum='2'
  // }
  console.log(route.path, 'route.path')
  data.addForm.orgcode = props.orgcode;
  data.addForm.deptId = props.orgcode;
  listQuery.orgCode = data.addForm.orgcode;
})
const frequencyDisplay = computed(() => {
  return `第${data.addForm.frequency || 'XX'}次会议`;
});
// 安委会会议
const typeNum = ref('2')
// 获取第几次
const retrievalTimes = (row) => {
  if (row) {
    let dataFrom = {
      orgcode: props.orgcode,
      quarter: row,
      year: data.addForm.year,
      type: typeNum.value
    };
    data.addForm.frequency = null;
    postApi(dataFrom, "/mosty-jcgl/meeting/selectYearMeetingCount")
      .then((res) => {
        res = res + 1;
        // frequency 用来提交接口（数字）
        data.addForm.frequency = res;
        // frequencyNum 用来渲染 option
        data.addForm.frequencyNum = res;
      })
      .catch(() => {
        console.log("获取失败");
      });
  } else {
    data.addForm.frequency = '';
    data.addForm.frequencyNum = 0;
  }
};

// 新的文件上传返回
const changeFile1 = (row) => {
  hyjyname.value = row[0].name;
};
const changeFile2 = (row) => {
  hyjyname2.value = row[0].name;
};
const changeFile = (row) => {
  filename.value = row[0].name;
};
const timeChange = (val) => {
  if (val) {
    let date = new Date(val);
    data.addForm.year = date.getFullYear();
  } else {
    data.addForm.year = '';
  }
}
function ChooesDdld(val) {
  zzlx.value = val;
  if (val == "01" && data.addForm.userid) {
    memberList.value = data.addForm.userid.split(',')
  }
  chooseUserVisible.value = true;
  singleShow.value = false;
}
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 + "(" + element.deptName + ")");
      arrid.push(element.id);
    }
    memberList.value = value.map((item) => {
      return item.id;
    });
    data.addForm.username = arr.join(",");
    data.addForm.userid = arrid.join(",");
  }
};
const CloseEvent = () => {
  if (props.saveBtnShow) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        data.addForm = {};
        emits("close");
      })
      .catch(() => {
        // catch error
      })
  } else {
    data.addForm = {};
    emits("close");
  }

};
function xqData(id) {
  getApi({}, "/mosty-jcgl/meeting/getTbMeetingById/" + id).then((res) => {
    if (res) {
      data.addForm = res;
    }
  });
}
const searchHander = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      loading.value = true;
      data.addForm.pics = data.addForm.pics ? data.addForm.pics.toString() : null;
      data.addForm.signin = data.addForm.signin ? data.addForm.signin.toString() : null;
      data.addForm.files = data.addForm.files ? data.addForm.files.toString() : null;
      data.addForm.otherFiles = data.addForm.otherFiles ? data.addForm.otherFiles.toString() : null;
      data.addForm.type = "2";
      data.addForm.state = '1'
      if (props.title === "添加安委会会议资料" || props.title === "添加安全领导小组会议资料") {
        postApi(data.addForm, "/mosty-jcgl/meeting/addMeeting").then(() => {
          loading.value = false;
          ElMessage.success("新增成功");
          emits("close");
        }).catch(() => {
          loading.value = false;
        });
      }
      if (props.title === "安委会会议资料修改" || props.title === "安全领导小组会议资料修改") {
        postApi(data.addForm, "/mosty-jcgl/meeting/editMeeting").then(() => {
          loading.value = false;
          ElMessage.success("修改成功");
          emits("close");
        }).catch(() => {
          loading.value = false;
        });
      }
    } else {
      ElMessage.warning("请输入必填项！！！");
    }
  });
};
</script>

<style lang="scss" scoped>
.el-form {
  display: block;
  margin: 10px 20px;
}

.right {
  width: 100%;
}

.bigBox {
  display: block !important;
  box-sizing: border-box;
}
</style>
