<template>
  <div>
    <div class="bigBox">
      <MOSTY.FromPage :title="props.title" @closeDialog="CloseEvent">
        <template #content>
          <div class="titpl">{{ planName }}</div>
          <div v-if="isShowfrom" class="form-container">
            <el-form :model="dialogForm" ref="ruleFormRef" width="1000px" label-width="140px"
              :disabled="!props.saveBtnShow" :rules="rules" :label-suffix="':'" style="" inline>
              <template v-for="(item, index) in dialogForm.itemList" :key="item">
                <MOSTY.Assort :title="'项目' + (index + 1)" />
                <el-form-item label="项目名称" :prop="'itemList.' + index + '.name'" :rules="rules.name">
                  <el-input v-model="item.name" style="width: 340px;" />
                </el-form-item>
                <el-form-item label="年度工作任务" :prop="'itemList.' + index + '.workContent'" :rules="rules.workContent">
                  <el-input v-model="item.workContent" style="width: 340px;" />
                </el-form-item>
                <el-form-item label="完成时限" :prop="'itemList.' + index + '.finishTime'" :rules="rules.finishTime">
                  <el-date-picker v-model="item.finishTime" type="data" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                    style="width: 340px;"></el-date-picker>
                </el-form-item>
                <el-form-item label="责任单位/部门" :prop="'itemList.' + index + '.orgcodename'" :rules="rules.orgcodename">
                  <el-input v-model="item.orgcodename" type="text" autosize disabled style="width: 340px;">
                    <template #append>
                      <el-button class='cursor' @click="ChooesDdld(index, item)">选择</el-button>
                    </template>
                  </el-input>
                </el-form-item>
              </template>
              <br>
              <div class="flex just-end mr20">
                <el-button type="primary" @click="addUserHander" v-if="props.Plantype != 'senh'">
                  <el-icon>
                    <CirclePlus />
                  </el-icon>
                  <span>增加项目</span>
                </el-button>
              </div>
              <el-form-item prop="files" :rules="[{ required: true, message: '请选择附件', trigger: 'blur' }]">
                <div class="flex flex-warp just-left " style="width: 100%;">
                  <div style="width: 96%;" class="mt15 flex">
                    <span class="red">*</span><label class="black">上传附件：</label>
                    <MOSTY.Upload :isAutoWidth="true" :nopicer="true" :isImg="false" :ShowfileList="true"
                      v-model="dialogForm.files" :limit="5" :showinput="true" :placeholder="'请上传pdf,ofd, doc, docx,wps'"
                      :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'wps']" style="margin-left: -20px;width: 890px;" />
                  </div>
                </div>
              </el-form-item>
            </el-form>
          </div>
          <div v-if="!isShowfrom" style="width: 80%;margin: 5px auto;">
            <div class="flex just-end">
              <el-button type="primary" v-loading="loadingShow" @click="onloadExecl">
                导出
              </el-button>
            </div>
            <div class="tab-top">
              <div><span>编制人：{{ dialogForm.summaryUserName }}</span>
                <span>编制时间：{{ dialogForm.xtCjsj }}</span>
              </div>
              <div><span>审核人：{{ dialogForm.judgeUsername }}</span>
                <span>审核时间：{{ dialogForm.judgeTime
                }}</span>
              </div>
            </div>
            <section class="eltabs3">
              <MOSTY.Table :table-columns="tabColumns" :tableloading="tableloading" :tableData="dialogForm.itemList"
                :tableHeight="'100%'" :isSelect="false" style="width: 100%;" :isSort="true">
                <template #orgName="{ row }">
                  <span v-for="it in row.orgList">{{ it.orgname }},</span>
                </template>
                <template #actions="{ row }">
                  <span class="operesee" @click="handleSee(row)">
                    <el-icon>
                      <Compass />
                    </el-icon>详情</span>
                </template>
              </MOSTY.Table>
            </section>
            <div class="mt10">
              <MOSTY.Upload :widthNumber="640" :nopicer="true" :isImg="false" :ShowfileList="true"
                v-model="dialogForm.files" :showinput="true" :placeholder="'请上传pdf,ofd, doc, docx,wps'"
                :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'wps']" :disabled="true" />
            </div>
            <div>
            </div>
          </div>
        </template>
        <template #footer>
          <!-- 新增修改的保存 -->

          <el-button type="primary" @click="save('0', ruleFormRef)" v-if="props.saveBtnShow && props.Plantype != 'baos'"
            :loading="loading">
            <el-icon>
              <DocumentChecked />
            </el-icon>
            <span>保存</span>
          </el-button>
          <el-button type="primary" @click="save('1', ruleFormRef)" v-if="showfb" :loading="loading">
            <el-icon>
              <Position />
            </el-icon><span>报送</span>
          </el-button>
          <el-button type="primary" @click="examineok('2')" v-if="props.Plantype == 'senh'" :loading="loading">
            <el-icon>
              <Check />
            </el-icon>
            <span>同意</span>
          </el-button>
          <el-button type="primary" @click="examineok('3')" v-if="props.Plantype == 'senh'" :loading="loading">
            <el-icon>
              <Close />
            </el-icon>
            <span>不同意</span>
          </el-button>
          <el-button type="primary" @click="CloseEvent">
            <el-icon>
              <DocumentDelete />
            </el-icon><span>返回</span>
          </el-button>
        </template>
      </MOSTY.FromPage>

    </div>
    <div v-if="planxqShow" class="dialog-box">
      <Planxq @close="closeAdd" v-if="planxqShow" :title="title" :rowObj="rowObj" :zbobj="dialogForm" />
    </div>
    <ChooseDept :data="taskList" :showDdld="showJkssbm" :searchType="'01'" @closezzjg="closeJhss" :Isstrictly='true'
      @listdata="getSonValue" :zzlx="zzlx" />
  </div>
</template>

<script setup>
// 引入
import { onMounted, ref, defineProps, getCurrentInstance, reactive } from "vue";
import { ElMessage } from "element-plus";
import { getItem } from "@/utils/storage";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import * as MOSTY from "@/components/MyComponents/index";
import ChooseDept from "@/components/MyComponents/ChooseDept/Departnobj.vue";
import Planxq from "./Planxq.vue";
import { exportXlsx } from "@/excel/Export2Excel.js";
const { proxy } = getCurrentInstance();
const emits = defineEmits(["close"]);
const ruleFormRef = ref(null)
const loadingShow = ref(false)
const showJkssbm = ref(false)
const tableloading = ref(false)
const planxqShow = ref(false)
const taskList = ref([])
const planName = ref(`${getItem("deptId").ssdwmc}${new Date().getFullYear()}年安全生产工作计划（要点）`)
const isShowfrom = ref(true)
const zzlx = ref(0)
const validateArray = (rule, value, callback) => {
  if (!Array.isArray(value)) {
    return callback(new Error('必须是一个数组'));
  }
  for (let i = 0; i < value.length; i++) {
    if (value[i]) {
      if (!value[i].name) {
        return callback(new Error(`请输入项目名称`));
      } else if (!value[i].workContent) {
        return callback(new Error(`请输入年度工作任务`));
      } else if (!value[i].orgcodename) {
        return callback(new Error(`请选择责任单位/部门`));
      } else if (!value[i].finishTime) {
        return callback(new Error(`请选择完成时限`));
      }
    } else {
      return callback(new Error(`请填写必填项，并上传附件`));
    }
  }
  callback();
};
const validateName = (rule, value, callback) => {
  console.log('value: ', value);
  if (!value) {
    return callback(new Error('请输入项目名称'));
  }
  callback();
};
const validateWorkContent = (rule, value, callback) => {
  console.log('value: ', value);
  if (!value) {
    return callback(new Error('请输入年度工作任务'));
  }
  callback();
};
const validateOrgcodename = (rule, value, callback) => {
  console.log('value: ', value);
  if (!value) {
    return callback(new Error('请选择责任单位/部门'));
  }
  callback();
};
const validateFinishTime = (rule, value, callback) => {
  console.log('value: ', value);
  if (!value) {
    return callback(new Error('请选择完成时限'));
  }
  callback();
};
const rules = reactive({
  // itemList: [{ required: true, validator: validateArray, trigger: 'blur' }],
  name: [{ required: true, validator: validateName, trigger: 'blur' }],
  workContent: [{ required: true, validator: validateWorkContent, trigger: 'blur' }],
  orgcodename: [{ required: true, validator: validateOrgcodename, trigger: 'blur' }],
  finishTime: [{ required: true, validator: validateFinishTime, trigger: 'blur' }],
})
const props = defineProps({
  saveBtnShow: {
    default: true,
    type: Boolean
  },
  title: String,
  Plantype: String,
  id: String,
  rwid: String,
});
// 数据
const rowObj = ref(null)
const loading = ref(false); //新增保存按钮截流
const showfb = ref(false);
const dialogForm = ref({
  orgCode: getItem("deptId").ssdwid,
  orgName: getItem("deptId").ssdwmc,
  itemList: [
    { name: '', workContent: '', orgcodename: '', finishTime: '', orgcodes: '' }
  ]
});
const tabColumns = reactive([
  {
    title: "项目名称",
    prop: "name"
  },
  {
    title: "年度工作任务内容",
    prop: "workContent"
  },
  {
    title: "责任单位/部门",
    prop: "orgName",
    slot: true
  },
  {
    title: "完成时限",
    prop: "finishTime"
  },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
// 初始化
onMounted(() => {
  if (props.saveBtnShow || props.Plantype == 'senh') {
    isShowfrom.value = true
  } else {
    isShowfrom.value = false
  }
  if (props.id) {
    getxqData(props.id)

  } else {
    showfb.value = true;
    dialogForm.value.orgCode = getItem("deptId").ssdwid;
    dialogForm.value.orgName = getItem("deptId").ssdwmc;
    planName.value = `${dialogForm.value.orgName}${new Date().getFullYear()}年安全生产工作计划（要点）`;
  }
});
function handleSee(row) {
  rowObj.value = row
  planxqShow.value = true
}
function closeAdd() {
  planxqShow.value = false
}
function ChooesDdld(val, item) {
  zzlx.value = val
  taskList.value = item.orgcodes ? item.orgcodes : []
  showJkssbm.value = true
}
function closeJhss() {
  taskList.value = []
  showJkssbm.value = false
}
function getSonValue(val) {
  let userarr = [];
  for (let i = 0; i < val.length; i++) {
    const element = val[i];
    userarr.push(element.orgName);
  }
  dialogForm.value.itemList[zzlx.value].orgcodes = val.map((item) => {
    return item.id;
  });
  dialogForm.value.itemList[zzlx.value].orgcodename = userarr.toString();

}

//获取详情
const getxqData = async (id) => {
  tableloading.value = true
  await getApi({ id }, "/mosty-jcgl/plansummary/getInfo").then((res) => {
    if (res) {
      dialogForm.value = res
      dialogForm.value.itemList.forEach(item => {
        item.orgcodename = item.orgList.map(it => { return it.orgname }).toString()
        item.orgcodes = item.orgList.map(it => { return it.orgcode })
      })

      if (dialogForm.value.state == '0' || dialogForm.value.state == '3') {
        showfb.value = true;
      } else {
        showfb.value = false;
      }
      planName.value = dialogForm.value.planName

      tableloading.value = false
    }
  }
  );
}
// 关闭
const CloseEvent = () => {
  if (props.saveBtnShow && props.Plantype != 'baos') {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        emits("close");
      })
      .catch(() => {
        // catch error
      })
  } else {
    emits("close");
  }

};
function addUserHander(params) {
  dialogForm.value.itemList.push({ name: '', workContent: '', orgcodename: '', finishTime: '' })
}
// 接收外层新增保存
const save = (val, ruleFormRef) => {
  ruleFormRef.validate((valid) => {
    if (valid) {
      loading.value = true
      dialogForm.value.state = val
      dialogForm.value.files = dialogForm.value.files ? dialogForm.value.files.toString() : nulls
      if (props.id) {
        postApi(dialogForm.value, "/mosty-jcgl/plansummary/editPlanSummary").then(() => {
          loading.value = false;
          ElMessage.success("修改成功");
          emits("close");
        }).catch(() => {
          loading.value = false;
        })
      } else {

        postApi(dialogForm.value, "/mosty-jcgl/plansummary/addPlanSummary").then(() => {
          loading.value = false;
          ElMessage.success("新增成功");
          emits("close");
        }).catch(() => {
          loading.value = false;
        })
      }
    } else {
      ElMessage.warning('请输入必填项！！！')
    }
  });

};
//审核
function examineok(val) {
  loading.value = true
  postApi({ id: dialogForm.value.id, state: val }, '/mosty-jcgl/plansummary/judegt').then(res => {
    ElMessage.success("审核完成");
    loading.value = false;
    let params = {
      id: props.rwid,
      sfyd: "1",
      clzt: "02"
    };
    postApi(params, "/mosty-jcgl/rw/updateRw")
      .then((res) => {
        // ElMessage.success("修改任务状态成功");
        emits("close");
      });

  }).catch(() => {
    loading.value = false;
  })
}

function onloadExecl() {
  let title = {
    name: '项目名称',
    workContent: '年度工作任务内容',
    orgName: '责任单位',
    finishTime: '完成时限'
  }
  loadingShow.value = true

  let data = JSON.parse(JSON.stringify(dialogForm.value.itemList))
  // let data = []

  for (let i = 0; i < data.length; i++) {
    const el = data[i];
    el.orgName = el.orgList && el.orgList.length > 0 ? el.orgList.map(it => { return it.orgname }).toString() : ''
  }
  let tablename = `${planName.value}.xlsx`
  exportXlsx(title, data, XLSX, tablename);
  loadingShow.value = false

}
</script>

<style lang="scss" scoped>
.eltabs3 {
  height: calc(100vh - 512px);
}

.red {
  text-align: right;
  color: red;
}

.black {
  // text-align: right;
  color: #000;
  width: 140px;
}

.el-form-item {
  margin-right: 10px;
}

.bigBox {

  .titpl {
    width: 100%;
    text-align: center;
    color: #000;
    font-size: 18px;
    margin-top: 10px;
  }

  .form-container {
    ::v-deep .el-form {
      display: block;
    }
  }


  .right {
    width: 100%;
    padding: 10px;
    box-sizing: border-box;
  }

  .btnBox {
    display: flex;
  }
}

.tab-top {
  display: flex;
  justify-content: space-between;
  margin: 10px auto;

  >div {
    >span {
      color: #000;
      font-size: 15px;
      margin-right: 20px;
    }
  }
}

.dialog-box {
  z-index: 3 !important;
}
</style>
