<template>
  <div>
    <LHeader :text="text"></LHeader>
    <van-form
      @submit="onSubmit"
      :scroll-to-error="true"
      :show-error="false"
      validate-trigger="onSubmit"
    >
      <div
        style="height: 1rem;font-family: '微软雅黑 Bold', '微软雅黑 Regular', '微软雅黑';font-weight: 700;line-height: 1rem;"
      >
        <img
          src="@/assets/accidentIcon/bookmark.svg"
          alt=""
          style="position: relative;top: 32%;transform: translateY(-50%);"
        />
        服务项目信息
      </div>
      <van-field
        readonly
        required
        name="userName"
        :value="form.userName"
        label="创建人员"
        placeholder="请输入"
        :rules="[{ required: true, message: '创建人员不能为空' }]"
      />
      <van-field
        readonly
        required
        name="deptName"
        :value="form.deptName"
        label="创建单位"
        placeholder="请输入"
        :rules="[{ required: true, message: '创建单位不能为空' }]"
      />
      <van-field
        required
        name="name"
        v-model="form.name"
        label="任务名称"
        placeholder="请输入"
        :rules="[{ required: true, message: '任务名称不能为空' }]"
      />

      <van-field
        required
        clickable
        name="projectName"
        :value="form.projectName"
        label="关联项目"
        placeholder="请选择"
        @click="show = true"
        :rules="[{ required: true, message: '关联项目不能为空' }]"
      />
      <!-- <van-popup v-model="showSource" position="bottom">
        <van-picker
          show-toolbar
          value-key="name"
          :columns="columnsSource"
          @confirm="onConSource"
          @cancel="showSource = false"
        />
      </van-popup> -->

      <van-field
        required
        name="buildingNames"
        :value="form.buildingNames"
        label="评估楼栋"
        placeholder="请输入"
        @click="getRiskList()"
        :rules="[{ required: true, message: '评估楼栋不能为空' }]"
      />
      <div
        style="height: 1rem;font-family: '微软雅黑 Bold', '微软雅黑 Regular', '微软雅黑';font-weight: 700;line-height: 1rem;"
      >
        <img
          src="@/assets/accidentIcon/bookmark.svg"
          alt=""
          style="position: relative;top: 32%;transform: translateY(-50%);"
        />
        任务组织与分配
      </div>
      <van-field
        required
        clickable
        name="deptName"
        :value="form.deptName"
        label="评估小组选择"
        placeholder="请选择"
        @click="selectDept()"
        :rules="[{ required: true, message: '评估小组不能为空' }]"
      />

      <van-field
        required
        clickable
        name="leaderUserName"
        :value="form.leaderUserName"
        label="评估小组组长"
        placeholder="请选择"
        @click="getLeaderUserList('leaderUser')"
        :rules="[{ required: true, message: '评估小组组长不能为空' }]"
      />

      <van-field
        clickable
        required
        name="workUserNames"
        :value="form.workUserNames"
        label="评估小组成员"
        placeholder="请选择"
        @click="getExecuteUser()"
        :rules="[{ required: true, message: '评估小组成员不能为空' }]"
      />

      <van-field
        :value="form.startTime"
        required
        name="startTime"
        label="任务开始时间"
        placeholder="请选择"
        @click="selectBeginTime('startTime')"
        :rules="[{ required: true, message: '任务开始时间不能为空' }]"
      />

      <van-field
        clickable
        :value="form.endTime"
        required
        name="endTime"
        label="任务结束时间"
        @click="selectBeginTime('endTime')"
        placeholder="请选择"
        :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
                required
                clickable
                name="approveUserName"
                :value="form.approveUserName"
                label="审批负责人"
                placeholder="请选择"
                @click="getLeaderUserList('approveUser')"
                :rules="[{ required: true, message: '事审批负责人不能为空' }]"
            /> -->
      <van-popup v-model="showTrouble" position="bottom">
        <van-picker
          show-toolbar
          value-key="nickName"
          :columns="columnsTrouble"
          @confirm="onConTrouble"
          @cancel="showTrouble = false"
        />
      </van-popup>

      <van-popup v-model="show" position="bottom" :style="{ height: '100%' }">
        <selectPeople @onClose="onClose" @onSave="onSave"></selectPeople>
      </van-popup>

      <van-popup
        v-model="riskModel"
        position="bottom"
        :style="{ height: '100%' }"
      >
        <div
          class="van-picker__toolbar"
          style="position: absolute;width: 100%;top: 0;"
        >
          <button
            type="button"
            class="van-picker__cancel"
            v-on:click="riskModel = false"
          >
            取消</button
          ><button
            type="button"
            class="van-picker__confirm"
            @click="onRiskList(riskList)"
          >
            确认
          </button>
        </div>
        <div style="display:flex;margin-top: 44px;">
          <van-checkbox-group
            v-model="riskList"
            ref="checkboxGroup"
            style="width: 100%;font-size: 18px;"
          >
            <van-checkbox
              shape="square"
              style="margin: 10px 0px;justify-content: center;"
              v-for="item in riskModelList"
              :key="item.id"
              :name="item"
              >{{ item[filedName] }}</van-checkbox
            >
          </van-checkbox-group>
          <div>
            <van-button type="primary" @click="checkAll">全选</van-button>
            <van-button type="info" @click="toggleAll">反选</van-button>
          </div>
        </div>
      </van-popup>

      <!-- 选择项目小组 -->
      <van-popup
        v-model="projectDept"
        position="bottom"
        :style="{ height: '100%' }"
      >
        <div
          class="van-picker__toolbar"
          style="position: absolute;width: 100%;top: 0;"
        >
          <button
            type="button"
            class="van-picker__cancel"
            v-on:click="
              {
                form.deptId = 0;
                projectDept = false;
              }
            "
          >
            取消</button
          ><button type="button" class="van-picker__confirm" @click="closeDept">
            确认
          </button>
        </div>
        <div style="display:flex;margin-top: 44px;">
          <selectDept @changeDept="changeDept"></selectDept>
        </div>
      </van-popup>

      <!-- 选择时间弹出层 -->
      <van-popup v-model="showTime" position="bottom">
        <van-datetime-picker
          type="datetime"
          @confirm="onConTime"
          @cancel="showTime = false"
          :min-date="minDate"
          v-model="currentDate"
        />
      </van-popup>

      <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 selectDept from "@/components/selectDept/index.vue";
import selectPeople from "@/views/riskProject/add/projectList.vue";
import { timestampToTime, generateId } from "@/utils/format";
import {
  getUserInfo,
  getLocalUserInfo,
  setLocalUserInfo
} from "@/utils/userInfo";
import { getFun, postFun } from "@/service/table.js";

export default {
  name: "risk-add",
  components: {
    LHeader,
    selectPeople,
    selectDept
  },
  beforeRouteLeave(to, from, next) {
    if (to.name != "matrix-grad") {
    }
    next();
  },
  data() {
    return {
      taskId: "",
      text: "创建任务",
      id: "",
      form: {
        name: ""
      },
      projectId: "", // 所属工程
      projectName: "", // 所属工程
      projectDirectorName: "", // 所属工程
      projectDirector: "", // 所属工程
      timeName: "", //
      userPrefix: "", //
      showProjectName: false,
      projectDept: false,
      riskModel: false,
      filedName: "",
      currentDate: new Date(),
      minDate: new Date(),
      showTime: false,
      show: false,
      riskList: [],
      riskModelList: [],
      columnsProjectName: [],
      factor: "", //风险因素
      showFactor: false,
      columnsFactor: [],
      source: "", //风险源
      showSource: false,
      columnsSource: [],
      trouble: "", //事故类型
      showTrouble: false,
      columnsTrouble: [],
      setRank: "", //风险定级
      showSetRank: false,
      riskRank: "", // 风险等级
      showRiskRank: false,
      showSetRankMode: false, // 是否显示定级方式
      setRankMode: "", // 定级方式文字
      setRankModeImg: [], // 定级方式图片
      location: "", //风险部位
      control: "", //管控层级
      showControl: false,
      showMainDutyDept: false,
      columnsMainDutyDept: [],
      mainDutyPeopLe: "", // 主责人员
      mainDutyPeopLeId: "",
      showMainDutyPeopLe: false,
      columnsMainDutyPeopLe: [],
      technology: "", //技术措施文字
      technologyImg: [], //技术措施图片
      administration: "", //管理措施文字
      administrationImg: [], //管理措施图片
      urgent: "", //应急措施文字
      urgentImg: [], //应急措施图片
      returnCause: "", // 退回原因
      isShowreturnCause: false
    };
  },
  created() {
    var userInfo = getUserInfo();
    this.form.userId = userInfo.userId;
    this.form.userName = userInfo.nickName;
    this.form.deptName = userInfo.dept.deptName;
    this.form.deptId = userInfo.dept.deptId;
    getFun(`/risk/plan/project/list`).then(res => {
      this.columnsSource = res.data;
    });
    // this.getList();
  },
  methods: {
    checkAll() {
      this.$refs.checkboxGroup.toggleAll(true);
    },
    toggleAll() {
      this.$refs.checkboxGroup.toggleAll();
    },
    // 确定时间的方法
    onConTime(date) {
      console.log(
        "%c [ date ]-293",
        "font-size:13px; background:pink; color:#bf2c9f;",
        date
      );
      let time = timestampToTime(date, "DT1", true);
      this.form[this.timeName] = time;
      this.showTime = false;
    },
    // 计划开始时间
    selectBeginTime(val) {
      this.showTime = true;
      this.timeName = val;
      this.currentDate = new Date();
    },
    getLeaderUserList(e) {
      if (!this.form.projectId) {
        this.$toast({
          title: "提示",
          message: "请选择关联项目!"
        });
        return false;
      }
      this.userPrefix = e;
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0
      });
      getFun(`/risk/plan/user/list/${this.form.deptId}`).then(res => {
        if (res.code == 200) {
          this.columnsTrouble = res.data;
          // 对数据进行赋值
          this.$toast.clear();
          this.showTrouble = true;
        } else {
          this.$toast.clear();
        }
      });
    },
    onRiskList(value) {
      console.log(
        "%c [ value ]-331",
        "font-size:13px; background:pink; color:#bf2c9f;",
        value
      );
      if (this.filedName == "nickName") {
        this.form.workUserIds = this.filterField("userId", value).join();
        this.form.workUserNames = this.filterField("nickName", value).join();
        console.log(
          "%c [ this.form.workUserNames ]-334",
          "font-size:13px; background:pink; color:#bf2c9f;",
          this.form.workUserNames
        );
      } else {
        this.form.buildingIds = this.filterField("id", value).join();
        this.form.buildingNames = this.filterField("name", value).join();
      }
      this.riskList = [];
      this.riskModel = false;
      // this.form[this.fieldName] = value.join();
    },
    selectDept() {
      this.projectDept = true;
    },
    changeDept(id, name) {
      console.log(id);
      this.form.deptId = id;
      this.form.deptName = name;
    },
    closeDept() {
      console.log(this.form.deptId);
      this.projectDept = false;
    },
    getExecuteUser() {
      if (!this.form.projectId) {
        this.$toast({
          title: "提示",
          message: "请选择关联项目!"
        });
        return false;
      }

      this.filedName = "nickName";
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0
      });
      getFun(`/risk/plan/user/list/${this.form.deptId}`).then(res => {
        if (res.code == 200) {
          this.riskModelList = res.data;
          // 对数据进行赋值
          this.$toast.clear();
          this.riskModel = true;
        } else {
          this.$toast.clear();
        }
      });
    },
    getRiskList() {
      if (!this.form.projectId) {
        this.$toast({
          title: "提示",
          message: "请选择关联项目!"
        });
        return false;
      }
      this.filedName = "name";
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0
      });
      getFun(`/risk/plan/building/list/${this.form.projectId}`).then(res => {
        if (res.code == 200) {
          this.riskModelList = res.data;
          // 对数据进行赋值
          this.$toast.clear();
          this.riskModel = true;
        } else {
          this.$toast.clear();
        }
      });
    },
    filterField(value, arr) {
      var arrs = [];
      arr.forEach(item => {
        arrs.push(item[value]);
      });
      return arrs;
    },
    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) {
      this.$toast.loading({
        message: "加载中...",
        forbidClick: true,
        loadingType: "spinner",
        duration: 0
      });
      let url = "/risk/plan";
      postFun(url, this.form)
        .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 => {
          // 定级方式
          this.urgentImg = (res.data.imgsysFiles2 || []).map(item => {
            return {
              ...item,
              url: item.filePath,
              file: new File([], item["fileName"], {})
            };
          });
          this.administrationImg = (res.data.imgsysFiles1 || []).map(item => {
            return {
              ...item,
              url: item.filePath,
              file: new File([], item["fileName"], {})
            };
          });
          this.technologyImg = (res.data.imgsysFiles0 || []).map(item => {
            return {
              ...item,
              url: item.filePath,
              file: new File([], item["fileName"], {})
            };
          });
          this.setRankModeImg = (res.data.imgsysFiles3 || []).map(item => {
            return {
              ...item,
              url: item.filePath,
              file: new File([], item["fileName"], {})
            };
          });

          // 请求人员列表
          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;

          //请求风险源
          postHdSource(`/risk/plan/project/list`).then(res => {
            this.columnsSource = res.data;
          });
        })
        .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?factorType=${this.factor}`).then(
        res => {
          this.columnsSource = res.data;
        }
      );
    },
    // 关联项目
    onConSource(value) {
      if (!value) {
        this.showSource = false;
        return;
      }
      this.form.projectId = value.id;
      this.form.projectName = value.name;
      this.showSource = false;
    },
    // 项目负责人
    onConTrouble(value) {
      if (!value) {
        this.showTrouble = false;
        return;
      }
      this.form[this.userPrefix + "Id"] = value.userId;
      this.form[this.userPrefix + "Name"] = value.nickName;
      console.log("this.form :>> ", this.form);
      this.showTrouble = false;
    },
    // 风险定级
    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);
    },

    // 选择作业人
    goSelPeoTwo(val) {
      this.peopleName = val;
      this.show = true;
    },
    onClose() {
      this.show = false;
    },
    onSave(e) {
      this.form.projectId = e.id;
      this.form.projectName = e.name;
      this.show = false;
    }
  },
  watch: {
    setRank(newVal, oldVal) {
      if (newVal == "其他定级方式") {
        this.showSetRankMode = true;
      } else {
        this.showSetRankMode = false;
      }
    }
  }
};
</script>
<style scoped>
/* @import url(); 引入css类 */
</style>
