<template>
  <div class="app-container">
    <el-descriptions title="检查任务">
      <el-descriptions-item label="检查名称">{{
        info.taskName
      }}</el-descriptions-item>
      <el-descriptions-item label="检查机构">{{
        info.checkOrgName
      }}</el-descriptions-item>
      <el-descriptions-item label="受检机构">{{
        info.beCheckedOrgName
      }}</el-descriptions-item>
      <el-descriptions-item label="检查角色"
        >{{
          info.checkRoles ? info.checkRoles.map((r) => r.name).join(",") : ""
        }}
      </el-descriptions-item>
      <el-descriptions-item label="开始日期"
        >{{ dayjs(info.planStartTime).format("YYYY-MM-DD") }}
      </el-descriptions-item>
      <el-descriptions-item label="截止日期"
        >{{ dayjs(info.planEndTime).format("YYYY-MM-DD") }}
      </el-descriptions-item>
      <el-descriptions-item label="创建时间"
        >{{ dayjs(info.planStartTime).format("YYYY-MM-DD") }}
      </el-descriptions-item>
      <el-descriptions-item label="检查组成员"
        ><el-input
          style="width: 80%; margin-top: -8px"
          placeHolder="请输入检查组成员"
          v-model="info.checkTeam"
          v-if="isRegister"
        ></el-input>
        <span v-else>{{ info.checkTeam }}</span>
      </el-descriptions-item>
      <el-descriptions-item label="检查状态"
        >{{ dayjs(info.planStartTime).format("YYYY-MM-DD") }}
      </el-descriptions-item>
    </el-descriptions>
    <div>
      <span style="margin-right: 20px">巡检区域</span>
      <el-button
        type="primary"
        size="mini"
        @click="onAddPoint()"
        v-if="isRegister"
        >新增检查内容</el-button
      >
    </div>
    <div class="content">
      <div class="area_content" v-for="area in info.checkList">
        <div>
          {{ area.areaName }}
        </div>
        <div>
          <div class="safetycheck_item" v-for="(item, index) in area.itemList">
            <span>{{ index + 1 }}、{{ item.itemName }}</span>
            <div class="safetycheck_point" v-for="point in item.pointList">
              <div>
                <span class="pointName"
                  ><i class="circle" /> {{ point.pointName }}</span
                >
                <el-radio-group v-model="point.status" v-if="isRegister">
                  <el-radio :label="0">正常</el-radio>
                  <el-radio :label="1">异常</el-radio>
                </el-radio-group>
                <span v-else>
                  <span v-if="point.status === 0">
                    <i class="circle" style="background-color: #1890ff" />
                    <label style="color: #1890ff"> 正常</label> </span
                  ><span v-else>
                    <i class="circle" style="background-color: #f5222d" />
                    <label style="color: #f5222d"> 异常</label>
                  </span>
                </span>
                <el-button
                  type="danger"
                  size="mini"
                  v-if="point.isAdd && isRegister"
                  style="margin-left: 50px"
                  @click="onDeletePoint(area, item, point)"
                  >移除</el-button
                >
              </div>
              <div v-if="point.status == 1">
                <el-form
                  :ref="'point_' + point.pointId"
                  :model="point"
                  :rules="exceptionRules"
                  label-width="100px"
                  v-if="isRegister"
                >
                  <el-form-item label="情况描述" prop="remark">
                    <el-input
                      v-model="point.remark"
                      style="width: 250px"
                      placeholder="请输入情况描述"
                      maxlength="255"
                    ></el-input>
                  </el-form-item>
                  <el-form-item label="异常图片" prop="image">
                    <imgUpload
                      type="more"
                      :value="
                        point.imgData
                          ? point.imgData.map((d) => d.imgPath).join(',')
                          : ''
                      "
                      @input="onImageChanged(point, $event)"
                    ></imgUpload>
                  </el-form-item>
                  <el-form-item label="整改期限" prop="rectificationDeadline">
                    <el-select
                      v-model="point.rectificationDeadline"
                      placeholder="请选择整改期限"
                    >
                      <el-option
                        v-for="item in dict.type.rectification_deadline"
                        :key="item.value"
                        :value="item.value"
                        :label="item.label"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                </el-form>
                <el-descriptions v-else :column="1">
                  <el-descriptions-item label="情况描述">{{
                    point.remark
                  }}</el-descriptions-item>
                  <el-descriptions-item label="整改期限">{{
                    getLabel(
                      dict.type.rectification_deadline,
                      point.rectificationDeadline
                    )
                  }}</el-descriptions-item>
                  <el-descriptions-item label="整改图片">
                    <div class="imageList">
                      <el-image
                        style="width: 100px; height: 100px"
                        v-if="point.imgData"
                        v-for="url in point.imgData"
                        :src="url"
                        :preview-src-list="point.imgData.map((d) => d.imgPath)"
                      >
                      </el-image></div
                  ></el-descriptions-item>
                </el-descriptions>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="dialog-footer">
      <el-button>关闭</el-button>
      <el-button
        @click="onGrant"
        v-if="showGrantBtn"
        v-hasPermi="['core:safetycheck:grant']"
        >授权</el-button
      >
      <el-button @click="onSave" v-if="showSaveBtn">保存</el-button>
      <el-button type="primary" @click="onSubmit()" v-if="showSaveBtn"
        >提交</el-button
      >
    </div>
    <SelectPoint
      ref="SelectPoint"
      :orgType="info.beCheckOrgType"
      @select="onSelectPoint"
    ></SelectPoint>
    <UserSelector
      ref="UserSelector"
      @select="onUserSelect"
      :selectLimit="1"
    ></UserSelector>
  </div>
</template>
<script>
import { mapGetters } from "vuex";
import * as api from "@/api/safetycheck/register.js";
import dayjs from "dayjs";
import SelectPoint from "../../ruleManager/dialog.select.point.vue";
import imgUpload from "@/components/ImageUpload/index.vue";
import UserSelector from "@/components/userSelector/index.vue";
import { getLabel } from "@/views/commonOption.js";
import { checkPermi } from "@/utils/permission.js";
export default {
  name: "safetyCheckRegister",
  data() {
    return {
      info: {},
      exceptionRules: {
        remark: [{ required: true, message: "请输入情况描述" }],
        rectificationDeadline: [{ required: true, message: "请选择整改期限" }],
      },
      pointIdsWhenAdd: [],
      mode: null,
    };
  },
  dicts: ["rectification_deadline", "sys_user_is_lock"],
  components: { SelectPoint, imgUpload, UserSelector },
  computed: {
    ...mapGetters(["orgId", "roleList", "userId"]),
    isRegister() {
      let r = this.mode === "register";
      return r;
    },

    showSaveBtn() {
      return (
        this.isRegister &&
        this.info.status != 3 &&
        (checkPermi(["core:safetycheck:register"]) ||
          this.info.grantUserId == this.userId)
      );
    },
    showGrantBtn() {
      let userRoleIds = this.roleList.map((r) => r.roleId);
      let taskRoleIds = this.info.checkRoles.map((r) => r.id);
      return (
        this.isRegister &&
        this.info.status != 3 &&
        userRoleIds.find((ur) => taskRoleIds.includes(ur))
      );
    },
  },
  mounted() {
    let id = this.$route.params.taskId;
    let mode = this.$route.query.mode;
    if (!mode) {
      mode = "info";
    }

    api.info(id).then((r) => {
      this.mode = mode;
      if (mode != "register") {
        this.info = r.data;
        return;
      }

      if (r.data.status == 3) {
        this.mode = "info";
        this.info = r.data;
        this.$message.info("任务已完成,将显示详情");
        return;
      }

      let userRoleIds = this.roleList.map((r) => r.roleId);
      let taskRoleIds = r.data.checkRoles.map((r) => r.id);

      if (
        (r.data.checkOrgId == this.orgId &&
          userRoleIds.find((ur) => taskRoleIds.includes(ur))) ||
        r.data.grantUserId == this.userId
      ) {
        this.info = r.data;
      } else {
        this.$message.warning("用户不能执行该任务");
        this.mode = "info";
      }
    });
  },
  methods: {
    dayjs,
    getLabel,
    onAddPoint() {
      this.pointIdsWhenAdd = [];
      this.info.checkList.forEach((a) => {
        a.itemList.forEach((i) => {
          i.pointList.forEach((p) => {
            this.pointIdsWhenAdd.push(p.pointId);
          });
        });
      });
      this.$refs.SelectPoint.show(this.pointIdsWhenAdd);
    },
    onSelectPoint(selectedList) {
      let hasNew = false;
      for (let index in selectedList) {
        let p = selectedList[index];
        if (this.pointIdsWhenAdd.indexOf(p.id) >= 0) {
          continue;
        }
        let info = this.info;
        let area = info.checkList.find((a) => a.areaId === p.areaId);
        if (!area) {
          area = { areaId: p.areaId, areaName: p.areaName, itemList: [] };
          info.checkList.push(area);
        }

        let item = area.itemList.find((i) => i.itemId == p.itemId);
        if (!item) {
          item = { itemId: p.itemId, itemName: p.itemName, pointList: [] };
          area.itemList.push(item);
        }

        let point = item.pointList.find((i) => i.pointId == p.id);
        if (!point) {
          point = {
            pointId: p.id,
            pointName: p.pointName,
            mustCheck: 1,
            isAdd: 1,
            status: 0,
            remark: null,
            imgData: null,
            rectificationDeadline: null,
            submitBy: null,
            submitTime: null,
          };

          item.pointList.push(point);
          hasNew = true;
        }
      }

      if (!hasNew) {
        this.$message.info("没有可新增的检查内容");
      }
    },
    onDeletePoint(area, item, point) {
      if (point.isAdd === 0) {
        this.$message.warning("不可删除计划的检查内容");
        return;
      }

      let index = item.pointList.indexOf(point);
      if (index >= 0) {
        item.pointList.splice(index, 1);
      }

      if (item.pointList.length === 0) {
        index = area.itemList.indexOf(item);
        area.itemList.splice(index, 1);
      }

      if (area.itemList.length === 0) {
        index = this.info.checkList.indexOf(area);
        this.info.checkList.splice(index, 1);
      }
    },
    onImageChanged(point, value) {
      point.imgData = value
        .split(",")
        .map((img) => ({ id: null, imgPath: img }));
    },
    onUserSelect(selected) {
      if (!selected || selected.length === 0) {
        this.$message.warning("请选择要授权的人员");
        return;
      }

      api
        .grant({
          planId: this.info.planId,
          beCheckedOrgId: this.info.beCheckedOrgId,
          taskId: this.info.id,
          ymdDate: this.info.ymdDate,
          userId: selected[0].id,
        })
        .then((r) => {
          this.$message.info("授权成功");
        });
      //调用授权
    },
    onGrant() {
      this.$refs.UserSelector.show();
    },
    onSave() {
      this.info.isSubmit = 0;
      api.submit(this.info).then((r) => {
        this.$message.info("保存成功");
      });
    },
    async onSubmit() {
      let isOk = true;
      let r = this.$refs;
      for (let p in this.$refs) {
        if (p.startsWith("point")) {
          try {
            isOk &= await this.$refs[p][0].validate();
          } catch (e) {
            isOk &= false;
            console.error(e);
          }
        }
      }
      if (isOk) {
        this.info.isSubmit = 1;
        api.submit(this.info).then((r) => {
          this.$message.info("提交成功");
        });
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.content {
  max-height: calc(100% - 300px);
  overflow-y: auto;
  margin-bottom: 20px;
  margin-top: 20px;
}
.area_content {
  border: #797979 1px solid;
  display: flex;
  flex-direction: row;
}

.content > .area_content:first-child {
  border-bottom: none;
}

.content > .area_content:last-child {
  border-bottom: #797979 1px solid;
}

.area_content > div:nth-child(1) {
  background-color: #f7f7f7;
  border-right: #797979 1px solid;
  padding-top: auto;
  width: 15%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  text-align: center;
}

.area_content > div:nth-child(2) {
  width: 80%;
  padding-left: 10px;
}

.safetycheck_item {
  margin: 10px;
  margin-bottom: 20px;
}

.safetycheck_point {
  padding-top: 10px;
  padding-left: 30px;
}
// .safetycheck_point > div:nth-child(1) {
//   margin-bottom: 15px;
// }
.pointName {
  width: 200px;
  display: inline-block;
}
.dialog-footer {
  width: 100%;
  text-align: right;
  border-top: #797979 1px solid;
  padding-top: 10px;
  padding-right: 30px;
  position: absolute;
  bottom: 30px;
  right: 0px;
}
.circle {
  display: inline-block;
  width: 5px;
  height: 5px;
  border-radius: 5px;
  background-color: #333333;
  border: none;
  margin-bottom: 3px;
}
</style>
