<template>
  <div>
    <LHeader :text="text"></LHeader>
    <van-form
      @submit="onSubmit"
      :scroll-to-error="true"
      :show-error="false"
      validate-trigger="onSubmit"
    >
      <van-field
        v-if="isShowreturnCause"
        v-model="returnCause"
        required
        readonly
        rows="1"
        autosize=""
        label="退回原因"
        name="returnCause"
        type="textarea"
      />
      <van-field
        v-if="!isShowreturnCause"
        required
        readonly
        clickable
        name="projectName"
        :value="projectName"
        label="所属项目"
        placeholder="请选择"
        @click="showProjectName = true"
        :rules="[{ required: true, message: '所属项目不能为空' }]"
      />
      <!-- {{headH}} -->
      <van-popup v-model="showProjectName" position="bottom">
        <van-picker
          show-toolbar
          value-key="projectName"
          :columns="columnsProjectName"
          @confirm="onConProjectName"
          @cancel="showProjectName = false"
        />
      </van-popup>

      <van-field
        readonly
        required
        clickable
        name="factor"
        :value="factor"
        label="风险因素"
        placeholder="请选择"
        @click="showFactor = true"
        :rules="[{ required: true, message: '风险因素不能为空' }]"
      />
      <van-popup v-model="showFactor" position="bottom">
        <van-picker
          show-toolbar
          value-key="factorType"
          :columns="columnsFactor"
          @confirm="onConFactor"
          @cancel="showFactor = false"
        />
      </van-popup>

      <van-field
        readonly
        required
        clickable
        name="source"
        :value="source"
        label="风险源"
        placeholder="请选择"
        @click="showSource = true"
        :rules="[{ required: true, message: '风险源不能为空' }]"
      />
      <van-popup v-model="showSource" position="bottom">
        <van-picker
          show-toolbar
          value-key="sourceName"
          :columns="columnsSource"
          @confirm="onConSource"
          @cancel="showSource = false"
        />
      </van-popup>

      <van-field
        readonly
        required
        clickable
        name="trouble"
        :value="trouble"
        label="事故类型"
        placeholder="请选择"
        @click="showTrouble = true"
        :rules="[{ required: true, message: '事故类型不能为空' }]"
      />
      <van-popup v-model="showTrouble" position="bottom">
        <van-picker
          show-toolbar
          value-key="accidentType"
          :columns="columnsTrouble"
          @confirm="onConTrouble"
          @cancel="showTrouble = false"
        />
      </van-popup>

      <van-field
        readonly
        clickable
        required
        label="事故定级"
        name="setRank"
        :value="setRank"
        placeholder="请选择"
        @click="showSetRank = true"
        v-if="!isShowreturnCause"
      />
      <van-popup v-model="showSetRank" position="bottom">
        <van-picker
          show-toolbar
          :columns="columnsSetRank"
          @confirm="onConSetRank"
          @cancel="showSetRank = false"
        />
      </van-popup>

      <van-field
        readonly
        required
        clickable
        name="riskRank"
        :value="riskRank"
        label="风险等级"
        placeholder="请选择"
        @click="myRiskRank"
        :rules="[{ required: true, message: '风险等级不能为空' }]"
      />
      <van-popup v-model="showRiskRank" position="bottom">
        <van-picker
          show-toolbar
          :columns="columnsRiskRank"
          @confirm="onConRiskRank"
          @cancel="showRiskRank = false"
        />
      </van-popup>

      <!-- <van-field
        v-model="riskRank"
        readonly
        name="riskRank"
        label="风险等级"
        placeholder="请选择"
        :rules="[{ required: true, message: '风险等级不能为空' }]"
      /> -->

      <van-field
        v-show="setRank=='其他定级方式'"
        v-model="setRankMode"
        name="setRankMode"
        label="定级方式"
        type="textarea"
        rows="1"
        autosize
        placeholder="请输入"
      />

      <van-field name="setRankModeFile" label=" "  v-show="setRank=='其他定级方式'">
        <template #input>
          <van-uploader
            multiple
            :max-count="5"
            upload-text="最多上传五个"
            v-model="setRankModeImg"
            accept="file"
            result-type="file"
            @delete="deleteFile(...arguments, 'setRankModeImg')"
          >
            <template slot="default">
              <!-- 11111111111 -->
              <div
                style="
                  width: 2.13333rem;
                  height: 2.13333rem;
                  background: #f7f8fa;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  flex-direction: column;
                "
              >
                <img
                  src="@/assets/upload/file.png"
                  alt=""
                  style="width: 0.64rem; height: 0.64rem"
                />
                <span class="van-uploader__upload-text">最多上传五个</span>
              </div>
            </template>
          </van-uploader>
        </template>
      </van-field>

      <van-field
        v-model="location"
        required
        name="location"
        label="风险部位"
        type="textarea"
        rows="1"
        autosize
        placeholder="请输入"
        :rules="[{ required: true, message: '风险部位不能为空' }]"
      />

      <van-field
        readonly
        clickable
        required
        name="control"
        :value="control"
        label="管控层级"
        placeholder="请选择"
        @click="showControl = true"
        :rules="[{ required: true, message: '管控层级不能为空' }]"
      />
      <van-popup v-model="showControl" position="bottom">
        <van-picker
          show-toolbar
          :columns="columnsControl"
          @confirm="onConControl"
          @cancel="showControl = false"
        />
      </van-popup>

      <van-field
        readonly
        clickable
        required
        name="mainDutyDept"
        :value="mainDutyDept"
        label="主责部门"
        :rules="[{ required: true, message: '主责部门不能为空' }]"
        placeholder="请选择"
        @click="showMainDutyDept = true"
      />
      <van-popup v-model="showMainDutyDept" position="bottom">
        <van-picker
          show-toolbar
          value-key="deptName"
          :columns="columnsMainDutyDept"
          @confirm="onConMainDutyDept"
          @cancel="showMainDutyDept = false"
        />
      </van-popup>

      <van-field
        readonly
        clickable
        required
        name="mainDutyPeopLe"
        :value="mainDutyPeopLe"
        label="主责人员"
        :rules="[{ required: true, message: '主责人员不能为空' }]"
        placeholder="请选择"
        @click="showMainDutyPeopLe = true"
      />
      <van-popup v-model="showMainDutyPeopLe" position="bottom">
        <van-picker
          show-toolbar
          value-key="userName"
          :columns="columnsMainDutyPeopLe"
          @confirm="onConMainDutyPeopLe"
          @cancel="showMainDutyPeopLe = false"
        />
      </van-popup>

      <van-field
        v-model="technology"
        name="technology"
        label="技术措施"
        type="textarea"
        rows="1"
        autosize
        placeholder="请输入"
      />
      <van-field name="technologyFile" label=" ">
        <template #input>
          <van-uploader
            multiple
            :max-count="5"
            upload-text="最多上传五个"
            v-model="technologyImg"
            accept="file"
            result-type="file"
            @delete="deleteFile(...arguments, 'technologyImg')"
          >
            <template slot="default">
              <!-- 11111111111 -->
              <div
                style="
                  width: 2.13333rem;
                  height: 2.13333rem;
                  background: #f7f8fa;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  flex-direction: column;
                "
              >
                <img
                  src="@/assets/upload/file.png"
                  alt=""
                  style="width: 0.64rem; height: 0.64rem"
                />
                <span class="van-uploader__upload-text">最多上传五个</span>
              </div>
            </template>
          </van-uploader>
        </template>
      </van-field>

      <van-field
        v-model="administration"
        name="administration"
        label="管理措施"
        type="textarea"
        rows="1"
        autosize
        placeholder="请输入"
      />
      <van-field name="administrationFile" label=" ">
        <template #input>
          <van-uploader
            multiple
            :max-count="5"
            upload-text="最多上传五个"
            v-model="administrationImg"
            accept="file"
            result-type="file"
            @delete="deleteFile(...arguments, 'administrationImg')"
          >
            <template slot="default">
              <!-- 11111111111 -->
              <div
                style="
                  width: 2.13333rem;
                  height: 2.13333rem;
                  background: #f7f8fa;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  flex-direction: column;
                "
              >
                <img
                  src="@/assets/upload/file.png"
                  alt=""
                  style="width: 0.64rem; height: 0.64rem"
                />
                <span class="van-uploader__upload-text">最多上传五个</span>
              </div>
            </template>
          </van-uploader>
        </template>
      </van-field>

      <van-field
        v-model="urgent"
        name="urgent"
        label="应急措施"
        type="textarea"
        rows="1"
        autosize
        placeholder="请输入"
      />

      <van-field name="urgentFile" label=" ">
        <template #input>
          <van-uploader
            multiple
            :max-count="5"
            upload-text="最多上传五个"
            v-model="urgentImg"
            accept="file"
            result-type="file"
            @delete="deleteFile(...arguments, 'urgentImg')"
          >
            <template slot="default">
              <!-- 11111111111 -->
              <div
                style="
                  width: 88px;
                  height: 88px;
                  background: #f7f8fa;
                  display: flex;
                  align-items: center;
                  justify-content: center;
                  flex-direction: column;
                "
              >
                <img
                  src="@/assets/upload/file.png"
                  alt=""
                  style="width: 0.64rem; height: 0.64rem"
                />
                <span class="van-uploader__upload-text">最多上传五个</span>
              </div>
            </template>
          </van-uploader>
        </template>
      </van-field>

      <div style="margin: 16px 16px 0">
        <van-button round block type="info" native-type="submit"
          >上报</van-button
        >
      </div>
    </van-form>
    <div style="margin: 10px 16px 0px; padding-bottom: 16px">
      <van-button round block type="warning" @click.native="cancel"
        >取消</van-button
      >
    </div>
  </div>
</template>

<script>
import LHeader from "@/components/header.vue";
import { getFun, postFun } from "@/service/table.js";
import {
  getFormList,
  postHdSource,
  postHdType,
  postHdPeople,
  postReAdd,
  postriskConiCause,
  postRiskShowMeasures,
} from "@/service/risk";
export default {
  name: "risk-add",
  components: {
    LHeader,
  },
  activated() {
    this.showSetRank = false; // 再次关闭弹出层 以防万一
    if (this.$route.params.status) {
      this.isShowreturnCause = true;
      this.text = "风险上报退回";
      this.taskId = this.$route.params.taskId;
      this.postReturnEcho();
    }
    this.getList();

    this.$bus.$on("riskLevelBus", (res) => {
      this.showSetRank = false; // 再次关闭弹出层 以防万一
      console.log(Boolean(res));
      if (res) {
        this.riskRank = res;
      } else {
        this.setRank = "";
      }
      // 销毁一下监听事件 不然会越加越多
      this.$bus.$off("riskLevelBus");
    });
  },
  beforeRouteLeave(to, from, next) {
    if (to.name != "matrix-grad") {
      (this.text = "新增风险"),
        (this.taskId = ""),
        (this.id = ""),
        (this.projectId = ""), // 所属工程
        (this.projectName = ""), // 所属工程
        (this.showProjectName = false),
        (this.columnsProjectName = []),
        (this.factor = ""), //风险因素
        (this.showFactor = false),
        (this.columnsFactor = []),
        (this.source = ""), //风险源
        (this.showSource = false),
        (this.columnsSource = []),
        (this.trouble = ""), //事故类型
        (this.showTrouble = false),
        (this.columnsTrouble = []),
        (this.setRank = ""), //风险定级
        (this.showSetRank = false),
        (this.columnsSetRank = ["矩阵式定级", "其他定级方式"]),
        (this.riskRank = ""), // 风险等级
        (this.showRiskRank = false),
        (this.columnsRiskRank = [
          "一般风险",
          "较小风险",
          "较大风险",
          "重大风险",
        ]),
        (this.setRankMode = ""), // 定级方式文字
        (this.setRankModeImg = []), // 定级方式图片
        (this.location = ""), //风险部位
        (this.control = ""), //管控层级
        (this.showControl = false),
        (this.columnsControl = ["项目级", "企业级"]),
        (this.mainDutyDept = ""), // 主责部门
        (this.mainDutyDeptId = ""),
        (this.showMainDutyDept = false),
        (this.columnsMainDutyDept = []),
        (this.mainDutyPeopLe = ""), // 主责人员
        (this.mainDutyPeopLeId = ""),
        (this.showMainDutyPeopLe = false),
        (this.columnsMainDutyPeopLe = []),
        (this.technology = ""), //技术措施文字
        (this.technologyImg = []), //技术措施图片
        (this.administration = ""), //管理措施文字
        (this.administrationImg = []), //管理措施图片
        (this.urgent = ""), //应急措施文字
        (this.urgentImg = []), //应急措施图片
        (this.returnCause = ""), // 退回原因
        (this.isShowreturnCause = false);
    }
    next();
  },
  data() {
    return {
      taskId: "",
      text: "新增风险",
      id: "",
      projectId: "", // 所属工程
      projectName: "", // 所属工程
      showProjectName: false,
      columnsProjectName: [],
      factor: "", //风险因素
      showFactor: false,
      columnsFactor: [],
      source: "", //风险源
      showSource: false,
      columnsSource: [],
      trouble: "", //事故类型
      showTrouble: false,
      columnsTrouble: [],
      setRank: "", //风险定级
      showSetRank: false,
      columnsSetRank: ["矩阵式定级", "其他定级方式"],
      riskRank: "", // 风险等级
      showRiskRank: false,
      columnsRiskRank: ["一般风险", "较小风险", "较大风险", "重大风险"],
      showSetRankMode: false, // 是否显示定级方式
      setRankMode: "", // 定级方式文字
      setRankModeImg: [], // 定级方式图片
      location: "", //风险部位
      control: "", //管控层级
      showControl: false,
      columnsControl: ["项目级", "企业级"],
      mainDutyDept: "", // 主责部门
      mainDutyDeptId: "",
      showMainDutyDept: false,
      columnsMainDutyDept: [],
      mainDutyPeopLe: "", // 主责人员
      mainDutyPeopLeId: "",
      showMainDutyPeopLe: false,
      columnsMainDutyPeopLe: [],
      technology: "", //技术措施文字
      technologyImg: [], //技术措施图片
      administration: "", //管理措施文字
      administrationImg: [], //管理措施图片
      urgent: "", //应急措施文字
      urgentImg: [], //应急措施图片
      returnCause: "", // 退回原因
      isShowreturnCause: false,
    };
  },
  created() {
    if (this.$route.params.status) {
      this.isShowreturnCause = true;
      this.text = "风险上报退回";
      this.taskId = this.$route.params.taskId;
      this.postReturnEcho();
    }
    this.getList();
  },
  methods: {
    async deleteFile(val, detail, key) {
      // console.log(val,detail)
      if (val.fileId) {
        let formdata = new FormData();
        formdata.append("key", val["fileId"]);
        let res = await postFun("/mobile/remove", formdata);
        if (res) {
          console.log(res);
          this.$toast({
            title: "提示",
            message: "删除成功!",
          });
        } else {
          console.log("删除失败");
          this[key].splice(detail.index, 0, val);
        }
      }
    },
    onSubmit(values) {
    
      let formdata = new FormData();
      formdata.append('id',this.id);
      formdata.append("pId", this.projectId);
      formdata.append("riskFactor", this.factor);
      formdata.append("riskSource", this.source);
      formdata.append("accidentType", this.trouble);
      formdata.append("level", values.setRank);
      formdata.append("riskLevel", this.riskRank);
      formdata.append("gradingMethod", this.setRankMode);
      formdata.append("riskPosition", this.location);
      formdata.append("controlLevel", this.control);
      formdata.append("responsibilityDept", this.mainDutyDeptId);
      formdata.append("responsibilityMember", this.mainDutyPeopLeId);
      formdata.append("technicalMeasures", this.technology);
      formdata.append("managementMeasures", this.administration);
      formdata.append("emergencyMeasure", this.urgent);

      // 放图片路径 因为formdat存数组会自动变成字符串所以次用这种追加字段的方式
      values.setRankModeFile.forEach((item) => {
        // 定级方式
        formdata.append("risk1[]", item.file);
      });
      // values.setRankModeFile.file
      values.technologyFile.forEach((item) => {
        // 技术措施
        formdata.append("risk2[]", item.file);
      });
      values.administrationFile.forEach((item) => {
        // 管理措施
        formdata.append("risk3[]", item.file);
      });
      values.urgentFile.forEach((item) => {
        // 应急措施
        formdata.append("risk4[]", item.file);
      });

      this.$toast.loading({
        message: "提交中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0,
      });
      let url = "/riskMain/add";
      if (this.taskId) {
        formdata.append("id", this.id);
        url = `/riskMain/editSave/${this.taskId}`;
      }
      postReAdd(url, formdata)
        .then((res) => {
          this.$toast.clear();
          this.$toast.success({
            message: "提交成功",
            duration: 2000,
          });
          history.go(-1);
        })
        .catch(() => {
          this.$toast.clear();
          this.$toast.fail("提交失败,请稍后再试");
        });
      this.$toast.clear();
    },

    // 请求表单数据
    getList() {
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0,
      });
      getFormList("/riskMain/add")
        .then((res) => {
          this.$toast.clear();
          this.columnsProjectName = res.data.projectInformations;
          this.columnsFactor = res.data.riskInventories;
          this.columnsMainDutyDept = res.data.organizationList;
        })
        .catch(() => {
          this.$toast.clear();
          this.$toast.fail("加载失败,请稍后再试");
        });
    },

    // 请求已退回详情数据
    postReturnEcho() {
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0,
      });
      postriskConiCause(`/riskMain/edit/${this.taskId}`)
        .then((res) => {
          let data = res.data.riskMain;
          let data1 = res.data.ResponsibilityMember;
          this.id=data.id;
          this.projectId = data.pId;
          this.riskRank = data.riskLevel;
          this.factor = data.riskFactor;
          this.source = data.riskSource;
          this.trouble = data.accidentType;
          this.setRank = data.level;
          this.setRankMode = data.grapingMethod;
          this.location = data.riskPosition;
          this.control = data.controlLevel;
          this.mainDutyDeptId = data.responsibilityDept;
          this.mainDutyPeopLeId = data.responsibilityMember;
          this.administration = data.managementMeasures;
          this.urgent = data.emergencyMeasure;
          this.mainDutyPeopLe = data.mainDutyPeopLe;
          this.mainDutyDept = data1.dept.deptName;
          this.technology = data.technicalMeasures;
          //  urgentImg administrationImg technologyImg setRankModeImg

          // 定级方式
          this.urgentImg = (res.data.imgsysFiles3 || []).map(item=>{return {...item,url:item.filePath}});
          this.administrationImg = (res.data.imgsysFiles2 || []).map(item=>{return {...item,url:item.filePath}});
          this.technologyImg = (res.data.imgsysFiles1 || []).map(item=>{return {...item,url:item.filePath}});
          this.tecsetRankModeImg = (res.data.imgsysFiles0 || []).map(item=>{return {...item,url:item.filePath}});
          console.log(
            data.riskFileList4,
            data.riskFileList3,
            data.riskFileList2,
            data.riskFileList1,
          );
          // this.technologyFile = res.data.riskFileList1.map(() => {
          //   return {
          //     ...item,
          //     url: item.filePath,
          //   };
          // });
          // this.urgentImg = data.riskFileList4.map(() => {
          //   console.log(111)
          //   return {
          //     ...item,
          //     url: item.filePath,
          //   };
          // });
          // this.administrationImg = data.riskFileList3.map(() => {
          //   return {
          //     ...item,
          //     url: item.filePath,
          //   };
          // });
          // this.technologyImg = data.riskFileList2.map(() => {
          //   return {
          //     ...item,
          //     url: item.filePath,
          //   };
          // });
          console.log("结果");
          // 请求人员列表
          let formdata = new FormData();
          formdata.append("organizationId", data.responsibilityDept);
          postHdPeople(`/riskMain/getUserList`, formdata).then((res) => {
            this.columnsMainDutyPeopLe = res.data;
            this.mainDutyPeopLe = this.columnsMainDutyPeopLe.filter((item) => {
              return item["userId"] == data.responsibilityMember;
            })[0]["userName"];
          });
          // console.log(data)
          this.$toast.clear();
          this.returnCause = res.data.reason;
        })
        .catch(() => {
          this.$toast.clear();
        });
    },

    // 所属项目
    onConProjectName(value) {
      if (!value) {
        this.showProjectName = false;
        return;
      }
      this.projectId = value.id;
      this.projectName = value.projectName;
      this.showProjectName = false;
    },
    // 风险因素
    onConFactor(value) {
      if (!value) {
        this.showFactor = false;
        return;
      }
      this.factor = value.factorType;
      this.showFactor = false;
      this.source = "";
      this.trouble = "";
      // 请求风险源
      postHdSource(`/riskMain/showSourceName/${this.factor}`).then((res) => {
        this.columnsSource = res.data;
      });
    },
    // 风险源
    onConSource(value) {
      if (!value) {
        this.showSource = false;
        return;
      }
      this.source = value.sourceName;
      this.showSource = false;
      this.trouble = "";
      // 请求事故类型
      postHdType(
        `/riskMain/showaccidentType/${this.factor}/${this.source}`
      ).then((res) => {
        this.columnsTrouble = res.data;
      });
    },
    // 事故类型
    onConTrouble(value) {
      if (!value) {
        this.showTrouble = false;
        return;
      }
      this.trouble = value.accidentType;
      this.showTrouble = false;
      // 请求三个措施
      postRiskShowMeasures(
        `/riskMain/showmeasures/${this.factor}/${this.source}/${this.trouble}`
      ).then((res) => {
        this.technology = res.data[0].measuresProject;
        this.administration = res.data[0].measuresAdministration;
        this.urgent = res.data[0].measuresEmergency;
      });
    },
    // 风险定级
    onConSetRank(value) {
      this.showSetRank = false;
      this.setRank = value;
      this.riskRank = "";
      if (this.setRank == "矩阵式定级") {
        this.showSetRank = false;
        this.$router.push({
          name: "matrix-grad",
        });
      }
    },
    // 自己定义风险等级点击方法
    myRiskRank() {
      if (this.setRank == "") {
        this.$toast("请先选择风险定级");
      } else if (this.setRank == "其他定级方式") {
        this.showRiskRank = true;
      }
    },
    // 风险等级
    onConRiskRank(value) {
      this.riskRank = value;
      this.showRiskRank = false;
    },

    // 管控层级
    onConControl(value) {
      this.control = value;
      this.showControl = false;
    },
    // 主责部门
    onConMainDutyDept(value) {
      this.mainDutyDeptId = value.deptId;
      this.mainDutyDept = value.deptName;
      this.showMainDutyDept = false;
      this.mainDutyPeopLe = "";
      // 请求主责人员
      let formdata = new FormData();
      formdata.append("organizationId", this.mainDutyDeptId);
      postHdPeople(`/riskMain/getUserList`, formdata).then((res) => {
        this.columnsMainDutyPeopLe = res.data;
      });
    },
    // 主责人员
    onConMainDutyPeopLe(value) {
      this.mainDutyPeopLeId = value.userId;
      this.mainDutyPeopLe = value.userName;
      this.showMainDutyPeopLe = false;
    },

    cancel() {
      this.$router.go(-1);
    },
  },
  watch: {
    setRank(newVal, oldVal) {
      if (newVal == "其他定级方式") {
        this.showSetRankMode = true;
      } else {
        this.showSetRankMode = false;
      }
    },
  },
};
</script>
<style scoped>
/* @import url(); 引入css类 */
</style>
