<template>
  <view class="shaftInspection">
    <!-- 导航栏 -->
    <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" />

        <TabContentItem
          v-for="(item, index) in tabList"
          :key="index"
          :ref="item.refName"
          v-show="activeTabIndex == index"
          :isDisable="isDisable"
        ></TabContentItem>
      </view>

      <view v-if="isOperationPermissions && !isDisable" class="fixed-btns">
        <view class="button-group">
          <!-- 保存草稿  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 class="btn-class" @tap="toNew"> 跳转新页面 </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 TabContentItem from "./model/tabContentItem.vue";
import {
  addLog,
  getLogContent,
  LOG_TYPE_ENUM,
  writeDarf,
  writeInspectionData,
} from "@/utils/IoReadingAndWriting.js";
import { pad_2_1_inspection_position, pad_2_1_floor } from "@/utils/dict.js";

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

export default {
  components: {
    Tabs,
    TabContentItem,
  },
  data() {
    return {
      tabList: [],
      activeTabIndex: 0,
      baseInfo: {}, // 基础信息
      tempForm: {
        // 对应每个tab下的数据   [示例     0: 数据]
      },
      detailsInfo: {}, // 详情
      isDisable: 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) {
      // 获取草稿数据
      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;
          uni.hideLoading();

          this.init();
        })
        .catch((error) => {
          uni.showToast({
            title: error.msg,

            icon: "none",
            duration: 1000,
          });
          uni.hideLoading();
        });
    }
  },
  mounted() {
    this.init();
  },

  methods: {
	  // 跳转新页面35.5
    toNew() {
      uni.navigateTo({
        url: "/pages/shaftInspection/shaftInspectionNew",
      });
    },
    init() {
      return new Promise((resolve, reject) => {
        this.tabList = pad_2_1_inspection_position.rows.map((item, index) => {
          return {
            name: item.dictLabel,
            value: item.dictValue,
            isVaild: false, // 校验通过
            // type: 1, // 枚举值
            position: pad_2_1_floor.rows,
            refName: `TabContentItem_${index}`,
            descript: "检查内容包括门禁、卫生、设备告警。",
          };
        });

        if (this.detailsInfo.inspectionType) {
          const fillCheck = this.detailsInfo.fillCheck.split(",");

          setTimeout(() => {
            this.tabList.forEach((item, index) => {
              item.isVaild = fillCheck.includes(item.value);
              this.tempForm[index] &&
                this.setComponentData(item.refName, this.tempForm[index]);
            });
          }, 500);
        } else {
          this.baseInfo = this.$store.state.temp_data;
        }

        resolve();
      });
    },
    // 回显数据
    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; // 是否禁用 1:已同步数据 0: 未同步数据
          uni.hideLoading();

          this.init();
        })
        .catch((error) => {
          uni.showToast({
            title: error.msg,
            icon: "none",
            duration: 1000,
          });
          uni.hideLoading();
        });
    },
    // 回显组件数据
    setComponentData(refName, componentData) {
      this.$refs[refName][0] && this.$refs[refName][0].setForm(componentData);
    },
    //--弹出对话框
    dialogInputConfirm2() {
      // uni.redirectTo({
      //   url: "/pages/home/home?tabIndex=1",
      //   success: () => {
      const userInfo = this.userInfo;
      const all_data = this.$store.state.all_data;
      const detailsInfo = this.detailsInfo;
      const baseInfo = this.baseInfo;

      const tempAllData = all_data.filter(
        (element) => element.uid != detailsInfo.uid
      );

      // console.log(
      //   "---删除内容",
      //   all_data.filter((element) => element.uid == detailsInfo.uid)
      // );

      // 更新巡检list
      this.$store.commit("SET_ALL_DATA", tempAllData);
      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();
    },

    // tab选中change 时间
    changeTab(index, item) {
      this.draft(this.activeTabIndex, false, false).then(() => {
        this.activeTabIndex = index;
      });
    },
    lookTable() {
      uni.navigateTo({
        url: "/pages/report/sampleTable?isJF=0",
      });
    },

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

    // 处理提交数据
    getParams() {
      const baseInfo = this.baseInfo;
      const tempForm = this.tempForm;
      const fillCheck = this.tabList
        .filter((item) => item.isVaild)
        .map((item) => item.value)
        .join(",");
			console.log("baseInfo",baseInfo)
			console.log("tempForm",tempForm)
			console.log("fillCheck",fillCheck)
      const temp = this.tabList.map((item, index) => {
        const items = ((tempForm[index] || {}).temp || []).map((ele) => {
          return {
            itemCode: ele.itemCode,
            measuredData: ele.measuredData,
            inspectionResult: ele.inspectionResult,
          };
        });

        // 一个tab栏下的数据，是否有异常
        const isException = ((tempForm[index] || {}).temp || []).filter(
          (item) => item.inspectionResult > 0
        ).length
          ? 1
          : 0;

        return {
          ...baseInfo,
          isSubmit: 1,
          conclusion: (tempForm[index] || {}).conclusion || "",
          fillCheck,
          position: item.value,
          isException,
          items,
        };
      });

			console.log("temp",temp)
      const item = {
        ...temp[0],
        isSubmit: 0,

        isException: temp.filter((item) => item.isException > 0).length ? 1 : 0, // 总的数据
        items: [],
        synchronization: 0, // 是否导出过
        submitTime: moment().format("yyyy-MM-DD"), // 记录提交时间
        submitMonth: moment().format("yyyy-MM"), // 记录提交月份
        originData: {
          baseInfo,
          tempForm,
        },
      };
			console.log("item",item)
      item[baseInfo.inspectionCode] = temp;
			console.log("item",baseInfo.inspectionCode)
      return item;
    },

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

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

          const params = this.getParams();
          const all_data = this.$store.state.all_data;
          const uid = this.detailsInfo.uid;
          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
          const userInfo = this.userInfo;
          this.$store.commit("SET_ALL_DATA", all_data);
          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", {}); // 缓存[巡检信息]
        }

        uni.showToast({
          icon: `${vaild ? "success" : "error"}`,
          title: `${vaild ? "提交成功" : "请完善填写内容"}`,
        });

        if (!vaild) {
          return;
        }

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

    // 保存草稿按钮
    draft(activeTabIndex, isSave = true, iSwtich = true) {
      let refName = this.tabList[activeTabIndex].refName;
      return new Promise((resolve, reject) => {
        this.$refs[refName][0].vaildForm().then(({ vaild, formData }) => {
          this.$refs.tabs
            .setTabVaild(activeTabIndex, vaild, iSwtich)
            .then(() => {
              this.tempForm[activeTabIndex] = formData;

              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})`,
                  "巡检模块"
                );
                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("日志文件写入成功");
                });
              }
              resolve();
            });
        });
      });
    },
  },
};
</script>

<style scoped lang="less">
.shaftInspection {
  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>
