<template>
  <!-- 井道巡检列表 -->
  <view class="container">
    <uni-nav-bar
      :fixed="true"
      background-color="rgba(214, 240, 255, 0.0)"
      status-bar
      rightWidth="300"
    >
      <block slot="left">
        <view class="" @click="back">
          <text class="iconfont icon-fanhui"></text>
        </view>
      </block>
      <block slot="right" class="nav-right">
        <view class="header-buttons">
          <view class="button" @click="lookTable">查看样表</view>
        </view>
      </block>
    </uni-nav-bar>
    <!-- 第二个模块 -->
    <view class="profile-section">
      <view class="profile-box">
        <view class="profile-left">
          <view class="avatar">
            <image
              src="@/static/img/add-img/defaultAvatar.png"
              mode="aspectFit"
            ></image>
          </view>
          <view class="info">
            <view class="describe">
              <view class="username">{{ userInfo.user }}</view>
              <view v-if="isSign && abnormalLengths" class="abnormal"
                >存在异常 {{ abnormalLengths }} 项</view
              >
            </view>
            <view class="describe">
              <view class="number"
                >巡检编号：<text class="value">{{ inspectionCode }}</text></view
              >
              <view v-if="isSign" class="number"
                >巡检时间：<text class="value">
                  {{ updateDate }}
                </text></view
              >
            </view>
          </view>
        </view>
        <!-- {{ isSubmit }} {{ isSign }} -->
        <view class="profile-right">
          <view
            v-if="!isSign"
            :disabled="!isSubmit"
            :class="{
              'record-button': true,
              'disabled-btn': !isSubmit,
            }"
            @click="toSign"
          >
            巡检人签字
          </view>
          <view
            v-else-if="detailsInfo.synchronization != 1"
            class="action-container"
          >
            <image
              class="sign-img"
              :src="detailsInfo.signImg"
              mode="aspectFit"
              @click="previewImage([detailsInfo.signImg], 0)"
            >
            </image>
            <button class="record-button small" @click="toSign">重签</button>
            <view class="inspection-button" @click="openDialog(true)"
              >数据同步</view
            >
          </view>
          <view
            class="action-container"
            v-if="detailsInfo.synchronization == 1"
          >
            <image
              class="sign-img no-border"
              :src="detailsInfo.signImg"
              mode="aspectFit"
              @click="previewImage([detailsInfo.signImg], 0)"
            >
            </image>
          </view>
        </view>
      </view>
    </view>
    <view v-if="!isSign" class="content-box">
      <!-- 左侧模块 -->
      <view class="left-side">
        <view
          v-for="(tab, index) in tabs.slice(0, 7)"
          :key="index"
          :class="['tab-item', { active: activeTab === index }]"
          @click="getActiveTab(index)"
        >
          {{ tab }}
        </view>
      </view>

      <!-- 右侧模块 -->
      <view class="right-side">
        <!-- 第一部分：按钮 -->
        <view class="button-group">
          <view class="button"
            >已巡检<text class="number">{{ inspectionNumber }}</text
            >个井道</view
          >
          <view class="button">
            <text class="iconfont icon-tixing"></text
            >请点击“需巡检井道”执行巡检</view
          >
        </view>

        <!-- 第二部分：卡片组 -->
        <view class="card-box">
          <view
            class="card-group"
            v-for="(item, index) in cardsInfo"
            :key="index"
          >
            <view class="card-title">{{ item.name }}</view>
            <view class="card-list">
              <view
                v-for="position in item.position"
                :key="position.dictValue"
                class="card"
                :class="{
                  status1: position.status == 1,
                  status2: position.status == 2,
                }"
                @click="
                  toShaftInspection(
                    item.value,
                    position.dictValue,
                    item.name + position.dictLabel
                  )
                "
              >
                <view class="card-content">
                  <view class="status-line">
                    <text
                      v-if="position.status == 0"
                      class="iconfont icon-weixunjian"
                    ></text>
                    <text
                      v-if="position.status == 1"
                      class="iconfont icon-wancheng"
                    ></text>
                    <text
                      v-if="position.status == 2"
                      class="iconfont icon-shibai1"
                    ></text>
                    <text v-if="position.isSubmit === 0" class="status-text"
                      >草稿</text
                    >
                    <text
                      v-else
                      :class="{
                        'status-text': true,
                        error: position.status == 2,
                      }"
                      >{{ position.statusLable }}</text
                    >
                  </view>
                  <view class="info-line">
                    <text class="info-text"
                      >{{ item.name }}{{ position.dictLabel }}</text
                    >
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </view>
    </view>
    <view v-else class="content-box">
      <!-- 左侧模块 -->
      <view class="left-side">
        <view
          v-for="(tab, index) in tabsDetail.slice(0, 7)"
          :key="index"
          :class="['tab-item', { active: activeTab === index }]"
          @click="getActiveTabDetails(index, tab)"
        >
          {{ tab }}
        </view>
      </view>

      <!-- 右侧模块 -->
      <view class="right-side">
        <!-- 第二部分：卡片组 -->
        <view class="card-box">
          <view
            class="card-group"
            v-for="(item, index) in cardsInfo"
            :key="index"
          >
            <view class="card-title">{{ item.name }}</view>
            <view class="card-list">
              <view
                v-for="position in item.position"
                :key="position.dictValue"
                class="card"
                :class="{
                  status1: position.status == 1,
                  status2: position.status == 2,
                }"
                @click="getDetailsItem(item.value, position.dictCode)"
              >
                <view class="card-content">
                  <view class="status-line">
                    <text
                      v-if="position.status == 0"
                      class="iconfont icon-weixunjian"
                    ></text>
                    <text
                      v-if="position.status == 1"
                      class="iconfont icon-wancheng"
                    ></text>
                    <text
                      v-if="position.status == 2"
                      class="iconfont icon-shibai1"
                    ></text>
                    <text v-if="position.isSubmit === 0" class="status-text"
                      >草稿</text
                    >
                    <text
                      v-else
                      :class="{
                        'status-text': true,
                        error: position.status == 2,
                      }"
                      >{{ position.statusLable }}</text
                    >
                  </view>
                  <view class="info-line">
                    <text class="info-text"
                      >{{ item.name }}{{ position.dictLabel }}</text
                    >
                  </view>
                </view>
              </view>
            </view>
          </view>
          <view v-if="isShow" class="card-group">
            <detail ref="detail" :detailsItem="detailsItem"></detail
          ></view>
        </view>
      </view>
    </view>
    <signDialog ref="signDialog" @confirm="handlePopupConfirm"></signDialog>
    <Dialog
      v-show="showSyncDialog"
      :list="list"
      @close="openDialog(false)"
    ></Dialog>
  </view>
</template>

<script>
import moment from "moment";
import { pad_2_1_inspection_position, pad_2_1_floor } from "@/utils/dict.js";
import {
  writeInspectionData,
  addLog,
  getLogContent,
  LOG_TYPE_ENUM,
} from "@/utils/IoReadingAndWriting.js";
import { getInspectionDetails } from "@/request/index.js";
import inspectApi from "@/api/inspect";
import signDialog from "@/components/signDialog.vue";
import detail from "./model/detail.vue";
import Dialog from "@/pages/inspectionManagement/dialog.vue";
import { sqlToData, dataToSql } from "./shared";
export default {
  components: {
    signDialog,
    detail,
    Dialog,
  },
  data() {
    return {
      tabs: ["所有井道"], // 选项卡内容
      tabsDetail: ["所有井道"],
      activeTab: 0, // 默认选中的选项卡
      inspectionNumber: 0, // 已巡检的井道数量
      cards: [
        "A座-1楼",
        "A座-2楼",
        "A座-3楼",
        "A座-4楼",
        "A座-5楼",
        "A座-6楼",
        "A座-7楼",
        "A座-8楼",
      ], // 卡片内容
      inspectionCode: "",
      cardsInfo: [], //卡片数据
      tabList: [],
      activeTabIndex: 0,
      baseInfo: {}, // 基础信息
      tempForm: {
        // 对应每个tab下的数据   [示例     0: 数据]
      },
      detailsInfo: {}, // 详情
      isDisable: false, // 禁用
      isSign: false, //签名状态
      isSubmit: 0, //提交状态
      uid: "",
      options: {}, //存储数据
      backValue: "",
      all_data: [], //所有数据
      detailsItem: {}, //单个井道详情
      isShow: false,
      showSyncDialog: false,
      list: [],
    };
  },
  computed: {
    userInfo() {
      return this.$store.state.now_user || {};
    },
    isOperationPermissions() {
      // 是否有操作权限
      const { uid, createByName } = this.detailsInfo;
      return !uid || (uid && createByName == this.userInfo.user);
    },
    abnormalLengths() {
      let allPoints = this.detailsInfo.originData.reduce((acc, cur) => {
        acc.push(...cur.position);
        return acc;
      }, []);
      let allItems = allPoints.reduce((acc, cur) => {
        acc.push(...cur.details);
        return acc;
      }, []);
      return allItems.filter((point) => point.inspectionResult === 1).length;
    },
    updateDate() {
      return moment(
        Number(this.detailsInfo.updateTime || this.detailsInfo.createTime)
      ).format("YYYY-MM-DD");
    },
  },
  onLoad(options) {
    this.options = options;
    this.backValue = this.options.backValue || "";
    this.isDisable = this.options.isDisable == 1 ? true : false;
    console.log("options.uid", this.options.uid);
    this.uid = this.options.uid || "";
  },
  onShow() {
    if (this.uid) {
      this.getDetails(this.uid);
    } else {
      this.init();
    }
    this.all_data = this.$store.state.all_data;
  },
  mounted() {},
  methods: {
    init() {
      return new Promise((resolve, reject) => {
        this.tabList = pad_2_1_inspection_position.rows.map((item, index) => {
          this.tabs.push(item.dictLabel);
          return {
            name: item.dictLabel,
            value: item.dictValue,
            isVaild: false, // 校验通过
            // type: 1, // 枚举值
            position: pad_2_1_floor.rows,
            refName: `TabContentItem_${index}`,
            descript: "检查内容包括门禁、卫生、设备告警。",
          };
        });
        this.cardsInfo = this.tabList;
        this.inspectionCode = `JDXJ${moment().format("yyyyMMDDHHmmss")}${
          Math.floor(Math.random() * 900) + 100
        }`;
        console.log("this.tabList", this.tabList);
        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();
      });
    },
    // 获取井道详情
    getDetailsItem(value, dictCode) {
      let item = this.detailsInfo.originData
        .find((building) => building.value === value)
        ?.position.find((pos) => pos.dictCode === dictCode);

      if (item.status < 1) {
        uni.showToast({
          title: "该井道暂无数据",
          icon: "none",
        });
      }
      this.detailsItem = item.details;
      this.isShow = true;
      console.log("this.detailsItem", this.detailsItem);
    },
    getActiveTab(index) {
      this.activeTab = index;
      console.log("this.activeTab", this.activeTab);
      if (this.activeTab == 0) {
        this.cardsInfo = this.tabList;
      } else {
        this.cardsInfo = [this.tabList[index - 1]];
      }
    },
    getActiveTabDetails(index, tab) {
      this.activeTab = index;

      // this.cardsInfo = [selected];
      // this.cardsInfo = [this.tabList[index]];
      if (this.activeTab == 0) {
        this.cardsInfo = this.tabList;
      } else {
        let selected = this.tabList.find((t) => t.name === tab);
        this.cardsInfo = [selected];
      }
      this.isShow = false;
    },
    // 回显数据
    getDetails(uid) {
      uni.showLoading();
      inspectApi
        .info(uid)
        .then((res) => {
          console.log(res);
          const detailsInfo = sqlToData(res);
          console.log("detailsInfo", detailsInfo);

          this.detailsInfo = detailsInfo;
          this.inspectionNumber = detailsInfo.inspectionNumber;
          if (detailsInfo.synchronization == 1) {
            // 已同步数据的查看详情时，只展示'已巡检'的井道信息，过滤未巡检的井道
            let defaultList = detailsInfo.originData;
            this.cardsInfo = this.tabList = defaultList.filter((building) => {
              building.position = building.position.filter(
                (pos) => pos.status == "1" || pos.status == "2"
              );
              return building.position.length;
            });
          } else {
            this.cardsInfo = this.tabList = detailsInfo.originData;
          }
          this.inspectionCode = detailsInfo.inspectionCode;
          // this.cardsInfo = this.tabList = detailsInfo.originData;
          this.isSubmit = this.detailsInfo.originData
            .reduce((acc, cur) => {
              acc.push(...cur.position);
              return acc;
            }, [])
            .every((pos) => pos.isSubmit === "" || pos.isSubmit === 1);
          console.log(this.detailsInfo);
          this.tabs = ["所有井道"];
          this.tabsDetail = ["所有井道"];
          this.isSign = !!this.detailsInfo.signImg;
          this.cardsInfo.forEach((item) => {
            this.tabs.push(item.name);
            this.tabsDetail.push(item.name);
          });
          if (this.isSign) {
            this.getActiveTabDetails(0);
          }
          this.isDisable = this.isDisable || detailsInfo.synchronization == 1; // 是否禁用 1:已同步数据 0: 未同步数据
          uni.hideLoading();
        })
        .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);
    },
    // 删除
    deleteClick() {
      this.$refs.inputDialog2.open();
    },
    toSign() {
      if (!this.isSubmit) return;
      this.$refs.signDialog.open();
    },
    // tab选中change 时间
    changeTab(index, item) {
      this.draft(this.activeTabIndex, false, false).then(() => {
        this.activeTabIndex = index;
      });
    },
    // 处理弹窗确认
    handlePopupConfirm(summary) {
      this.detailsInfo.isSign = this.isSign = true; // 回显到文字显示区域
      this.detailsInfo.signImg = summary; // 回显到文字显示区域
      const isException = this.detailsInfo.originData
        .reduce((acc, cur) => {
          acc.push(...cur.position);
          return acc;
        }, [])
        .some((item) => item.status == 2);
      this.detailsInfo.isException = isException ? 1 : 0; // 巡检异常
      this.submit(
        "sign",
        this.detailsInfo.signImg,
        this.detailsInfo.isException
      );
    },

    // 提交
    submit(type = "sign", value = "", isException) {
      const all_data = this.all_data; //获取全部数据
      let params = this.detailsInfo;
      params.signImg = value;
      console.log("all_data", all_data);
      const index = all_data.findIndex((element) => element.uid == this.uid);
      console.log("签字获取数据", params);
      all_data[index] = params;
      const logContent = getLogContent(LOG_TYPE_ENUM.sign, "签字", "机房巡检");
      // 更新巡检list
      console.log("all_data存储", all_data);
      console.log("all_data一个", all_data[index]);
      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;
      log_list.push(logContent);
      this.$logApi.addlog(logContent);
      this.$store.commit("SET_LOG_LIST", log_list);
      addLog(log_list).then((res) => {
        console.log("日志文件写入成功");
      });
      if (type === "sign") {
        inspectApi.updateSignImg({
          id: params.id,
          signImg: params.signImg,
          synFlag: 0,
          isException,
        });
      }
      uni.showToast({
        title: type == "sign" ? "签字成功" : "同步成功",
        icon: "success",
      });

      this.getActiveTabDetails(0);
    },
    lookTable() {
      uni.navigateTo({
        url: "/pages/report/sampleTable?isJF=0",
      });
    },
    // 跳转到具体的井道
    toShaftInspection(value, dictValue, location) {
      uni.navigateTo({
        url: `/pages/shaftInspection/shaftInspectionNew?value=${value}&dictValue=${dictValue}&inspectionCode=${this.inspectionCode}&location=${location}&uid=${this.uid}&backValue=${this.backValue}`,
      });
    },
    back() {
      if (this.backValue === "home") {
        uni.navigateTo({
          url: "/pages/home/home",
        });
      } else {
        uni.navigateTo({
          url: `/pages/inspectionManagement/index`,
        });
      }
    },
    openDialog(val) {
      if (val) {
        let data = dataToSql(this.detailsInfo);
        this.list = [
          {
            ...data,
            id: this.uid,
          },
        ];
      } else {
        this.list = [];
        this.tabs = ["所有井道"];
        this.tabsDetail = ["所有井道"];
        this.getDetails(this.uid);
      }
      this.showSyncDialog = val;
    },
    previewImage(images, index) {
      uni.previewImage({
        current: index,
        urls: images,
      });
    },
  },
};
</script>

<style lang="less" scoped>
/* 导航栏样式 */

.nav-right {
  width: 192px;
}

.header-buttons {
  display: flex;
  align-items: center;
  margin-left: auto; // 将按钮组推到最右侧

  .button {
    width: 89.6px;
    height: 28.8px;
    background: #ffffff;
    border-radius: 14.4px;
    margin-left: 12.8px;
    font-family: PingFangSC-Regular;
    font-size: 12.8px;
    color: #000000;
    line-height: 28.8px;
    font-weight: 400;
    text-align: center;
  }
}

.container {
  background-image: linear-gradient(115deg, #e8f0fb 0%, #e1ebfa 100%);
  padding: 0 25.6px;
  height: 100vh;
  overflow: hidden;

  .profile-section {
    width: 100%;
    margin-bottom: 12.8px;

    .profile-box {
      background-color: #fff;
      border-radius: 9.6px;
      padding: 12.8px 25.6px;
      display: flex;
      justify-content: space-between;
      align-items: center;

      .profile-left {
        display: flex;
        align-items: center;

        .avatar {
          position: relative;
          width: 51.2px;
          height: 51.2px;
          border-radius: 50%;
          overflow: hidden;
          margin-right: 9.6px;

          image {
            width: 100%;
            height: 100%;
          }

          .change-password {
            position: absolute;
            bottom: 0;
            left: 0;
            right: 0;
            background-color: rgba(0, 0, 0, 0.5);
            text-align: center;
            height: 17.6px;
            font-family: PingFangSC-Regular;
            font-size: 9.6px;
            color: #ffffff;
            line-height: 16px;
            font-weight: 400;
          }
        }

        .info {
          margin-right: 9.6px;
          .username {
            font-size: 16px;
            color: #000000;
            line-height: 22.4px;
            font-weight: 500;
            margin-bottom: 7.2px;
            margin-right: 10px;
          }

          .number {
            font-size: 12.8px;
            color: #4a4a4a;
            line-height: 22.4px;
            font-weight: 400;
            margin-right: 9.6px;
            .value {
              color: #000000;
            }
          }
          .describe {
            display: flex;
            .abnormal {
              color: #fff;
              line-height: 22.4px;
              height: 22.4px;
              padding: 0 8px;
              font-size: 12px;
              background-color: #f55a42;
              border-radius: 11px;
            }
          }
        }
      }

      .profile-right {
        display: flex;

        .inspection-button {
          width: 89.6px;
          height: 28.8px;
          background-image: linear-gradient(105deg, #68acfb 0%, #3774f6 100%);
          border-radius: 14.4px;
          font-family: PingFangSC-Regular;
          font-size: 12.8px;
          color: #ffffff;
          line-height: 28.8px;
          font-weight: 400;
          margin-right: 12.8px;
        }

        .record-button {
          display: block;
          width: 115.2px;
          height: 28.8px;
          background: #ffffff;
          border: 0.8px solid rgba(55, 116, 246, 1);
          border-radius: 14.4px;
          font-family: PingFangSC-Regular;
          font-size: 12.8px;
          color: #3774f6;
          line-height: 28.8px;
          font-weight: 400;
          display: flex;
          justify-content: center;
          &.disabled-btn {
            color: #c7c7c7;
            background-color: #f9f9f9;
            border-color: #f2f2f2;
          }
        }
        .action-container {
          display: flex;
          .record-button.small {
            width: 75px;
            margin-right: 10px;
          }
          .inspection-button {
            display: flex;
            align-items: center;
            justify-content: center;
            width: 115.2px;
            height: 28.8px;
            color: #fff;
            background-image: linear-gradient(180deg, #3773f6 0%, #2c57f6 99%);
            box-shadow: 0px 8px 19.2px 0px rgba(51, 104, 246, 0.24);
            border-radius: 14.4px;
          }
          .sign-img {
            width: 80px;
            height: 28.8px;
            margin-right: 10px;
            border: 1px solid #ccc;
            border-radius: 3px;
            &.no-border {
              border: none;
            }
          }
        }
      }
    }
  }

  /* 页面容器 */
  .content-box {
    width: 100%;
    height: calc(100vh - 190px);
    border-radius: 9.6px;
    overflow: hidden;
    background-color: #ffffff;
    display: flex;

    /* 左侧模块 */
    .left-side {
      width: 120px;
      height: 100%;
      background-color: #f9f9f9;
      display: flex;
      flex-direction: column;
      align-items: center;
      padding-top: 12.8px;

      .tab-item {
        width: 100%;
        height: 38.4px;
        display: flex;
        font-size: 12.8px;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        color: #4a4a4a;
        cursor: pointer;

        &.active {
          font-weight: bold;
          color: #000;
          background-color: #ffffff;
        }
      }
    }

    /* 右侧模块 */
    .right-side {
      flex: 1;
      padding: 12.8px 18.4px;
      display: flex;
      flex-direction: column;

      .button-group {
        display: flex;
        margin-bottom: 12.8px;
        .button {
          height: 27.2px;
          background-color: rgba(55, 116, 246, 0.08);
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 11.2px;
          color: #3774f6;
          border-radius: 3.2px;

          &:first-child {
            width: 97.6px;
            font-size: 11.2px;
            color: #4a4a4a;
            letter-spacing: 0;
            font-weight: 400;
            .number {
              color: #000000;
              font-weight: 500;
            }
          }

          &:last-child {
            flex: 1;
            margin-left: 9.6px;
            padding: 0 9.6px;
            text-align: left;
            display: flex;
            justify-content: flex-start;
            font-size: 11.2px;
            color: #4a4a4a;
            letter-spacing: 0;
            font-weight: 400;
            .icon-tixing {
              color: #3774f6;
              font-size: 9.6px;
              margin-right: 6.4px;
            }
          }
        }
      }

      .card-box {
        overflow: auto;

        .card-group {
          flex: 1;

          .card-title {
            font-size: 12.8px;
            font-weight: bold;
            color: #333333;
            margin: 12.8px 0;
          }

          .card-list {
            display: flex;
            flex-wrap: wrap;
            gap: 12.8px;

            .card {
              width: 105.6px;
              height: 51.2px;
              background-color: #f9f9f9;
              border-radius: 6.4px;
              padding: 6.4px 10.312px;
              box-sizing: border-box;
              &.status1 {
                background: #f3f7ff;
              }
              &.status2 {
                background: #fff5f4;
              }

              .card-content {
                display: flex;
                flex-direction: column;
                justify-content: space-between;

                .status-line {
                  display: flex;
                  align-items: center;
                  margin-bottom: 3px;

                  .iconfont {
                    font-size: 12px;
                    margin-right: 6.4px;
                    &.icon-weixunjian {
                      color: #959595;
                    }
                    &.icon-shibai1 {
                      color: #ff4a34;
                    }
                    &.icon-wancheng {
                      color: #3774f6;
                    }
                  }

                  .status-text {
                    font-size: 12px;
                    color: #7c7c7c;
                    text-align: center;
                    line-height: 16.5px;
                    font-weight: 400;
                    &.error {
                      color: #f55a42;
                    }
                  }
                }

                .info-line {
                  margin-left: 20px;
                  font-size: 12px;
                  color: #000000;
                  line-height: 16.5px;
                  font-weight: 400;
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
