<template>
  <view class="inspectionContent">
    <!-- 导航栏 -->
    <uni-nav-bar
      :fixed="true"
      background-color="rgba(214, 240, 255, 0.0)"
      status-bar
      rightWidth="300"
    >
      <block slot="left">
        <view class="uni-nav-bar-text" @click="back">
          <text class="iconfont icon-Arrow-Left"></text
        ></view>
      </block>

      <block slot="right">
        <view class="nav-right">
          <view
            v-if="isOperationPermissions"
            class="uni-nav-bar-text"
            @click="deleteClick"
          >
            <text class="iconfont icon-delete"></text
          ></view>

          <view class="look-from" @click="lookTable">
            <text class="iconfont icon-see-s"></text>
            查看样表</view
          ></view
        >
      </block>
    </uni-nav-bar>

    <view class="content">
      <view class="base-info">
        <view class="title">{{ baseInfo.recordName }}</view>
        <view class="base-row">
          <view class="base-row-item"
            ><text class="name">巡检编号</text
            ><text class="text">{{ baseInfo.inspectionCode }}</text>
          </view>
          <view class="base-row-item"
            ><text class="name">巡检时间</text
            ><text class="text">{{ baseInfo.inspectionTime }}</text>
          </view>
          <view class="base-row-item"
            ><text class="name">巡检人</text
            ><text class="text">{{ baseInfo.inspectionBy }}</text>
          </view>
        </view>

        <image
          class="bg-img"
          mode="aspectFill"
          src="@/static/img/add-img/inspection_bg.png"
        ></image>
      </view>

      <view class="main">
        <view class="content_header">巡检项目</view>

        <!-- tabls -->
        <Tabs class="tabs" ref="tabs" :options="tabList" @change="changeTab" />

        <GatherDataCenter
          v-show="activeTabIndex == 0"
          :isDisable="isDisable"
          ref="GatherDataCenter"
        />
        <ShieldedComputerRoom
          ref="ShieldedComputerRoom"
          v-show="activeTabIndex == 1"
        />
        <BatteryRoom
          ref="BatteryRoom"
          :isDisable="isDisable"
          v-show="activeTabIndex == 2"
        />

        <ComputerRoomDuty
          ref="ComputerRoomDuty"
          :isDisable="isDisable"
          v-show="activeTabIndex == 3"
        ></ComputerRoomDuty>

        <DutyHandover
          ref="DutyHandover"
          :isDisable="isDisable"
          v-show="activeTabIndex == 4"
        ></DutyHandover>
      </view>

      <view v-if="isOperationPermissions && !isDisable" class="fixed-btns">
        <view class="button-group">
          <!-- isSubmit 标识： 0 是草稿态；  1 是正式提交 -->
          <view
            v-if="!detailsInfo.isSubmit || detailsInfo.isSubmit == 0"
            class="btn-draft btn-class"
            @tap="draft(activeTabIndex)"
          >
            保存草稿
          </view>
          <view class="btn-class" @tap="submit"> 提交 </view>
        </view>
      </view>
    </view>

    <!-- 退出账号弹出 -->
    <uni-popup ref="inputDialog2" type="dialog">
      <uni-popup-dialog
        ref="inputClose2"
        mode="base"
        title="确定删除巡检内容？"
        @confirm="dialogInputConfirm2"
      >
      </uni-popup-dialog>
    </uni-popup>
  </view>
</template>

<script>
import moment from "moment";
import Tabs from "./model/tabs.vue";
import BatteryRoom from "./model/batteryRoom.vue";
import GatherDataCenter from "./model/gatherDataCenter.vue";
import ShieldedComputerRoom from "./model/shieldedComputerRoom.vue";
import ComputerRoomDuty from "./model/computerRoomDuty.vue";
import DutyHandover from "./model/dutyHandover.vue";
import {
  addLog,
  getLogContent,
  LOG_TYPE_ENUM,
  writeDarf,
  writeInspectionData,
} from "@/utils/IoReadingAndWriting.js";
import {
  pad_1_1_inspection_position,
  pad_1_2_inspection_position,
  pad_1_3_inspection_position,
  pad_room_type,
} from "@/utils/dict.js";

import { getInspectionDetails, getDarft } from "@/request/index.js";

export default {
  components: {
    Tabs,
    BatteryRoom,
    GatherDataCenter,
    ShieldedComputerRoom,
    ComputerRoomDuty,
    DutyHandover,
  },
  data() {
    return {
      tabList: [
        {
          name: "汇聚机房",
          isVaild: false, // 校验通过
          position: pad_1_1_inspection_position.rows,
          descript:
            "痕迹检查地面、墙壁、天花板、是否有裂痕、水渍，机房内是否有鼠患、蚁患、蟑螂活动的痕迹，温湿度取最高值，正常室温：20~25℃，湿度：40~60%。",
        },
        {
          name: "屏蔽机房",
          isVaild: false, // 校验通过
          position: pad_1_2_inspection_position.rows,
          descript: "UPS检查包含UPS主机、UPS输入柜、UPS输出柜。",
        },
        {
          name: "电池间",
          isVaild: false, // 校验通过
          position: pad_1_3_inspection_position.rows,
          descript: "",
        },
        {
          name: "机房值班",
          isVaild: false, // 校验通过
          descript: "记录哪些人员进出机房、总计次数。",
          position: [],
        },
        {
          name: "值班交接",
          isVaild: false, // 校验通过
          descript: "未完事项交换。",
          position: [],
        },
      ],
      activeTabIndex: 0,
      baseInfo: {}, // 基础信息
      tempForm: {
        // 对应每个tab下的数据   [示例     0: 数据]
      },
      detailsInfo: {}, // 详情
      isDisable: false, // 禁用
      loading: false,
    };
  },
  computed: {
    userInfo() {
      return this.$store.state.now_user || {};
    },
    isOperationPermissions() {
      // 是否有操作权限
      const { uid, createByName } = this.detailsInfo;
      return !uid || (uid && createByName == this.userInfo.user);
    },
  },
  onLoad(options) {
    this.isDisable = options.isDisable == 1 ? true : false;

    if (options.uid) {
      // 获取详情
      this.getDetails(options.uid);
    } else if (options.isDarf) {
      // 获取草稿数据
      // const darf_data = this.$store.state.darf_data;
      uni.showLoading();

      getDarft()
        .then((res) => {
          const darf_data = res || {};
          this.baseInfo = darf_data.originData.baseInfo;
          this.tempForm = darf_data.originData.tempForm;
          this.detailsInfo = darf_data;
          this.init();

          uni.hideLoading();
        })
        .catch((error) => {
          uni.showToast({
            title: error.msg,
            icon: "none",
            duration: 1000,
          });
          uni.hideLoading();
        });
    }
  },
  mounted() {
    this.init();
  },

  methods: {
    init() {
      pad_room_type.rows.forEach((item, index) => {
        this.tabList[index].value = item.dictValue;
      });

      if (this.detailsInfo.inspectionType) {
        const fillCheck = this.detailsInfo.fillCheck.split(",");
        this.tabList.forEach((item, index) => {
          item.isVaild = fillCheck.includes(item.value);

          this.tempForm[index] &&
            this.setComponentData(index, this.tempForm[index]);
        });
      } else {
        this.baseInfo = this.$store.state.temp_data;
      }
    },
    // 回显数据
    getDetails(uid) {
      uni.showLoading();

      getInspectionDetails(uid)
        .then((res) => {
          const detailsInfo = res;

          this.baseInfo = detailsInfo.originData.baseInfo;
          this.tempForm = detailsInfo.originData.tempForm;
          this.detailsInfo = detailsInfo;

          this.isDisable = this.isDisable || detailsInfo.synchronization == 1;
          uni.hideLoading();

          this.init();
        })
        .catch((error) => {
          uni.showToast({
            title: error.msg,
            icon: "none",
            duration: 1000,
          });
          uni.hideLoading();
        });
    },
    // 回显组件数据
    setComponentData(activeTabIndex, componentData) {
      let refName = "";
      switch (activeTabIndex) {
        case 0:
          refName = "GatherDataCenter";
          break;
        case 1:
          refName = "ShieldedComputerRoom";

          break;
        case 2:
          refName = "BatteryRoom";

          break;
        case 3:
          refName = "ComputerRoomDuty";
          break;

        case 4:
          refName = "DutyHandover";
          break;
      }
      this.$refs[refName].setForm(componentData);
    },

    //--弹出对话框
    dialogInputConfirm2() {
      const all_data = this.$store.state.all_data;
      const baseInfo = this.baseInfo
      const detailsInfo = this.detailsInfo;
      const tempAllData = all_data.filter(
        (element) => element.uid != detailsInfo.uid
      );

      // 更新巡检list
      this.$store.commit("SET_ALL_DATA", tempAllData);
      const userInfo = this.userInfo;
      const inspectList =  tempAllData.filter((item) => item.createByName == userInfo.user)
      writeInspectionData(
        inspectList,
        userInfo.user
      );

      if(!detailsInfo.uid){
        // 清空草稿数据
        this.$store.commit("SET_DARF_DATA", {}); // 缓存[巡检信息]
        writeDarf("").then((res) => {
          console.log("写入草稿文件成功");
        });
      }

      // 更新日志
      const log_list = this.$store.state.log_list;
      const logContent = getLogContent(
        LOG_TYPE_ENUM.delete,
        `${baseInfo.recordName}(${baseInfo.inspectionCode})`,
        "巡检模块"
      );
      logContent.inspectionType = baseInfo.inspectionType;
	  this.$logApi.addlog(logContent)
      log_list.push(logContent);
      this.$store.commit("SET_LOG_LIST", log_list);

      addLog(log_list).then((res) => {
        console.log("日志文件写入成功");
      });

      uni.showToast({
        icon: `success`,
        title: `删除成功`,
      });
      uni.redirectTo({
        url: "/pages/home/home?tabIndex=1",
        success() {
          uni.hideLoading();
        },
      });
    },
    // 删除
    deleteClick() {
      this.$refs.inputDialog2.open();
    },

    lookTable() {
      uni.navigateTo({
        url: "/pages/report/sampleTable?isJF=1",
      });
    },

    // tab选中change 时间
    changeTab(index, item) {
      this.draft(this.activeTabIndex, false, false).then(() => {
        this.activeTabIndex = index;
      });
    },

    back() {
      uni.navigateBack();
    },

    // 处理提交数据
    getParams() {
      const tabList = this.tabList;
      const tempForm = this.tempForm;
      const baseInfo = this.baseInfo;

      const fillCheck = tabList
        .filter((item) => item.isVaild)
        .map((item) => item.value)
        .join(",");
      let temp = {
        ...baseInfo,
        isSubmit: 0,
        fillCheck,
        isException: "",
        roomWatch: "",
        dutyHandover: "",
        successor: "",
        handoverPerson: "",
      };
      const tempItems = [];

      tabList.forEach((element, index) => {
        if (Array.isArray(tempForm[index])) {
          tempItems.push(...tempForm[index]);
        } else {
          temp = {
            ...temp,
            ...tempForm[index],
          };
        }
      });


      const items = tempItems.map((item) => {
        return {
          itemCode: item.itemCode,
          measuredData: item.measuredData,
          notes: item.notes,
          inspectionResult: item.inspectionResult,
          roomType: item.roomType,
        };
      });
      const isException = items.filter((item) => item.inspectionResult > 0)
        .length
        ? 1
        : 0;

      return {
        ...temp,
        items,
        isException,
        synchronization: 0, // 是否导出过
        submitTime: moment().format("yyyy-MM-DD"), // 记录提交时间
        submitMonth: moment().format("yyyy-MM"), // 记录提交月份

        originData: {
          baseInfo,
          tempForm,
        },
      };
    },

    // 提交按钮
    submit() {
      this.draft(this.activeTabIndex, false, false).then(() => {
        const vaild = this.$refs.tabs.isAllVails();
        const uid = this.detailsInfo.uid;
        this.loading = true;

        if (vaild) {
          /**
           * 校验通过,
           *  1.更新 store 数据,
           * 2. 巡检list文件
           * 3.清空草稿文件数据、store草稿数据
           */

          const params = this.getParams();
          const all_data = this.$store.state.all_data;
          params.isSubmit = 1;

          let logContent = "";

          // 新增 or 编辑
          if (uid) {
            const index = all_data.findIndex((element) => element.uid == uid);
            params.uid = uid;
            all_data[index] = params;
            logContent = getLogContent(
              LOG_TYPE_ENUM.edit,
              `${params.recordName}(${params.inspectionCode})`,
              "巡检模块"
            );
          } else {
            params.uid = new Date().getTime(); // 唯一标识 pad 端使用
            all_data.push(params);
            logContent = getLogContent(
              LOG_TYPE_ENUM.add,
              `${params.recordName}(${params.inspectionCode})`,
              "巡检模块"
            );
          }
		
          // 更新巡检list
          this.$store.commit("SET_ALL_DATA", all_data);
          const userInfo = this.userInfo;
          const inspectList =  all_data.filter((item) => item.createByName == userInfo.user)

          writeInspectionData(
            inspectList,
            userInfo.user
          );

          // 更新日志
          const log_list = this.$store.state.log_list;
          logContent.inspectionType = params.inspectionType;
		  this.$logApi.addlog(logContent)
          log_list.push(logContent);
          this.$store.commit("SET_LOG_LIST", log_list);

          addLog(log_list).then((res) => {
            console.log("日志文件写入成功");
          });

          // 清空草稿数据
          this.$store.commit("SET_DARF_DATA", {}); // 缓存[巡检信息]
          writeDarf("").then((res) => {
            console.log("写入草稿文件成功");
          });

          // 清空基础缓存信息
          this.$store.commit("SET_TEMP_DATA", {}); // 缓存[巡检信息]


          this.loading = false;
        }

        uni.showToast({
          icon: `${vaild ? "success" : "error"}`,
          title: `${vaild ? "校验通过" : "请完善填写内容"}`,
        });

        if (!vaild) {
          this.loading = false;

          return;
        }

        uni.redirectTo({
          url: "/pages/home/home?tabIndex=1",
          success() {
            uni.hideLoading();
          },
        });
      });
    },

    // 保存草稿按钮
    draft(activeTabIndex, isSave = true, iSwtich = true) {
      let refName = "";
      return new Promise((resolve, reject) => {
        switch (activeTabIndex) {
          case 0:
            refName = "GatherDataCenter";
            break;
          case 1:
            refName = "ShieldedComputerRoom";

            break;
          case 2:
            refName = "BatteryRoom";

            break;
          case 3:
            refName = "ComputerRoomDuty";
            break;

          case 4:
            refName = "DutyHandover";
            break;
        }
        if (this.loading) return;

        this.$refs[refName].vaildForm().then(({ vaild, formData }) => {
          this.$refs.tabs
            .setTabVaild(activeTabIndex, vaild, iSwtich)
            .then(() => {
              this.tempForm[activeTabIndex] = formData;
              this.loading = true;

              if (isSave) {

                // 写入草稿文件   更新  store 草稿内容
                const params = this.getParams();
                params.isSubmit = 0;
                this.$store.commit("SET_DARF_DATA", params);
                // 缓存草稿
                writeDarf(params).then((res) => {
                  console.log("写入草稿文件成功");
                  uni.showToast({
                    icon: "success",
                    title: "保存草稿成功",
                  });
                });

                // 新增日志信息
                const logContent = getLogContent(
                  LOG_TYPE_ENUM.darf,
                  `${params.recordName}(${params.inspectionCode})`,
                  "巡检模块"
                );
                logContent.inspectionType = params.inspectionType;
				this.$logApi.addlog(logContent)
                const log_list = this.$store.state.log_list;
                log_list.push(logContent);
                this.$store.commit("SET_LOG_LIST", log_list);
                addLog(log_list).then((res) => {
                  console.log("日志文件写入成功");
                });

                this.loading = false;
              } else {
                this.loading = false;
              }

              resolve();
            });
        });
      });
    },
  },
};
</script>

<style scoped lang="less">
.inspectionContent {
  width: 100%;
  height: 100%;
  background-image: linear-gradient(
    180deg,
    #f8fafc 0%,
    rgba(255, 255, 255, 0) 91%
  );

  .content {
    position: absolute;
    top: 0;

    width: 100%;
    background-image: linear-gradient(
      0deg,
      #f3f6fa 0%,
      rgba(130, 153, 238, 0.73) 49%,
      #5474e8 100%
    );
    height: calc(100vh - 44px - var(--status-bar-height) - 20px);
    background-size: 100% 40rpx;
    background-repeat: no-repeat;

    padding-bottom: 160px;
    .content_header {
      font-size: 18px;
      color: #000000;
      line-height: 26px;
      font-weight: 500;
    }
    .main {
      width: 100%;
      height: 100%;
      overflow: auto;
      padding: 20px 0;
      position: relative;
      padding: 0 20px 20px 20px;
      .tabs {
        margin: 16px 0;
      }
    }
  }

  // 基础信息
  .base-info {
    height: 170px;
    padding: 20px 24px;
    background-image: linear-gradient(
      90deg,
      #e9f7fe 0%,
      #dceffe 40%,
      #d5ebfd 66%,
      #c9e8fe 100%
    );
    background-repeat: no-repeat;
    background-size: 100% 100%;
    margin-bottom: 16px;
    padding-top: 80px;
    position: relative;
    .bg-img {
      right: 0;
      bottom: 0;
      position: absolute;
      width: 250px;
      height: 100px;
    }
    .title {
      font-size: 26px;
      color: #000000;
      line-height: 34px;
      font-weight: 600;
      margin-bottom: 16px;
    }
    .base-row {
      display: flex;
      align-items: center;
      .base-row-item {
        margin-right: 32px;
      }
    }
    .name {
      font-size: 14px;
      color: #7c7c7c;
      font-weight: 400;
    }
    .text {
      margin-left: 12px;
      font-size: 14px;
      color: #000000;
      font-weight: 400;
    }
  }

  .fixed-btns {
    height: 70px;
    background-image: linear-gradient(-87deg, #ecf1f4 3%, #eaf6fc 100%);
    width: 100%;
    display: flex;
    align-items: center;
    justify-content: center;
    .button-group {
      display: flex;
      align-items: center;
      background-image: linear-gradient(-87deg, #ecf1f4 3%, #eaf6fc 100%);
      .btn-class {
        width: 180px;
        height: 40px;
        background-image: linear-gradient(180deg, #3773f6 0%, #2c57f6 99%);
        box-shadow: 0px 10px 24px 0px rgba(51, 104, 246, 0.24);
        border-radius: 27px;
        font-size: 18px;
        color: #ffffff;
        text-align: center;
        font-weight: 400;
        text-align: center;
        line-height: 40px;
        margin-right: 24px;
      }
      .btn-draft {
        background: #fff;
        border: 1px solid #3773f6;
        color: #3773f6;
        box-shadow: none;
      }
    }
  }

  // 导航栏样式
  .uni-nav-bar-text {
    height: 36px;
    width: 36px;
    background: #ffffff;
    border: 0.4px solid rgba(224, 224, 224, 1);
    border-radius: 18px;
    border-radius: 50%;
    color: #333;
    text-align: center;
    .iconfont {
      font-size: 20px;
      line-height: 36px;
    }
  }

  .nav-right {
    display: flex;
    align-items: center;
    .icon-delete {
      font-size: 14px;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .look-from {
      margin-left: 12px;
      height: 36px;
      line-height: 36px;
      padding: 0 12px;
      background: #ffffff;
      border: 0.4px solid rgba(224, 224, 224, 1);
      border-radius: 10px;
      .iconfont {
        margin-top: 5px;
        margin-right: 5px;
        font-size: 14px;
      }
    }
  }
}
</style>
