<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="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">
              <MOSTY.Select v-model="dialogForm.level" filterable :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"'>
              <div style="width: 100%;">
                <MOSTY.DictRidioAndSelect :dictData="D_BZ_SF" v-model="dialogForm.sfgk" selectType="radio"
                  :disabled="false" />
              </div>
            </el-form-item>
            <el-form-item label="课题小组成员：" prop="username" style="width: 100%">
              <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="content" style='width:100%;'>
              <el-input v-model="dialogForm.content" autosize type="textarea" />
            </el-form-item>
            <el-form-item label="主要成果：" prop="zycg" style='width:100%;'>
              <el-input v-model="dialogForm.zycg" autosize type="textarea" />
            </el-form-item>
            <el-form-item label="备注：" style='width:100%;'>
              <el-input v-model="dialogForm.bz" maxlength="500" autosize type="textarea" 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"
                :ShowfileList="true" :placeholder="'请上传pdf,ofd, doc, docx,wps'"
                :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'wps']" @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']"
                :disabled="!props.saveBtnShow">
              </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>

    <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, deleteApi, putApi, postApi } from "@/api/tobAcco_api.js";
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_LWJB } = proxy.$dict("D_BZ_SF", "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 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);
onMounted(() => {


});
const rules = reactive({
  titlename: [{ required: true, message: "请输入课题名称", trigger: "change" }],
  content: [{ required: true, message: "请输入主要内容", trigger: "change" }],
  zycg: [{ required: true, message: "请输入主要成果", trigger: "change" }],
  username: [{ 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 title = ref("");
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");
  }

};

//获取详情
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;
}
const getSonValue = (value) => {
  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();
};

// 接收外层新增保存
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 = '3';
      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("请输入必填项!");
    }
  });
};
</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>
