<template>
  <div class="taskPhotoTaking">
    <van-nav-bar class="navBar" left-arrow title="生动化陈列" @click-left="onClickLeft">
      <template #right v-if="formData">
        <span
          v-if="formData.processStatus != 1 && editFlag"
          @click="onSubmit"
          style="
            color: white;
            background: rgb(0, 87, 186);
            display: block;
            padding: 6px 10px;
            border-radius: 6px;
          "
          >保存</span
        >
      </template>
    </van-nav-bar>
    <div class="content" v-if="formData">
      <div class="container">
        <van-form ref="tabstoreVal">
          <div v-for="(item, index) in formData.collectionItemList" :key="index">
            <div v-if="item.answerType == 'zp'" class="formLabel z-cell">
              <van-cell>
                <template #title>
                  <!-- <span v-if="item.isMust == 0" class="van-f-red">*</span> -->
                  <div class="headline">
                    <span class="headlineIcon"></span>
                    <span class="headlineTitle"
                      >上传照片
                      <span v-if="formData.sdhclPhotoNum" style="color: red">
                        (拍全产品和道具，至少{{ formData.sdhclPhotoNum }}张)
                      </span>
                    </span>
                  </div>
                  <!-- 操作说明图片和电话 -->
                  <taskTips
                    v-if="item.contactPhone || item.examplePhoto"
                    :contactPhone="item.contactPhone"
                    :examplePhoto="item.examplePhoto">
                  </taskTips>
                </template>
              </van-cell>
              <deleteUploadImgTaskPhoto
                :imgs="item.fileInfoList"
                ref="taskPhoto"
                :formData="formData"
                :storeGroupId="storeGroupId"
                :taskIds="taskIds"
                :visitsId="visitsId"
                :collectionItemId="item.collectionId"
                :putInCode="formData.putInCode"
                :photoIdentifyType="formData.photoIdentifyType"
                @upDataDetail="getDetaile"
                :pictureSource="item.pictureSource"
                :continuousShoot="item.continuousShoot"
                :insert="insert"
                :fileInfoList="item.fileInfoList"
                :objectType="objectType"
                :editFlag="editFlag"></deleteUploadImgTaskPhoto>
            </div>
          </div>
        </van-form>
      </div>
      <div class="dataList" v-if="dataList">
        <div class="headline" style="margin-top: 10px">
          <span class="headlineIcon"></span>
          <span class="headlineTitle">门店参与的陈列任务要求</span>
        </div>
        <div class="dataItem" v-for="(item, index) in dataList">
          <div class="itemTop">
            <div class="itemIndex">
              <p style="margin: 5px 0 10px 0">
                {{ index + 1 }}、<span>{{ item.taskName }}</span>
              </p>
            </div>
            <div class="itemHtml" v-html="item.displayInstructions"></div>
          </div>
          <div class="itemBottom" v-if="insert == 'false'">
            <van-button
              round
              type="primary"
              @click="openDialog(item)"
              v-if="item.taskPhotoConditionPassed == 1"
              >通过</van-button
            >
            <van-button
              round
              type="danger"
              @click="openDialog(item)"
              v-if="item.taskPhotoConditionPassed == 0"
              >不通过</van-button
            >
            <!-- <img
              v-if="item.taskPhotoConditionPassed == 1"
              @click="openDialog(item)"
              :src="require('@/assets/taskPhotoSu.png')" />
            <img
              v-if="item.taskPhotoConditionPassed == 0"
              @click="openDialog(item)"
              :src="require('@/assets/taskPhotoErr.png')" /> -->
          </div>
        </div>
      </div>
    </div>
    <el-dialog
      title="识别结果"
      :visible.sync="vanPopup"
      width="80%"
      :append-to-body="true"
      :close-on-click-modal="false"
      @close="vanPopup == false"
      custom-class="identifyResultdialog">
      <!-- 识别结果 -->
      <div class="identifyResult" v-if="taskPhotoRecognitionResult" style="padding: 0 10px">
        <div class="resultContent">
          <el-table
            :data="taskPhotoRecognitionResult"
            :span-method="taskObjectSpanMethod"
            border
            class="table-headermd1"
            style="width: 100%">
            <el-table-column label="" type="index" width="50px" align="center" />
            <el-table-column label="产品" prop="skuProductName" align="center" />
            <el-table-column
              label="识别排面数"
              prop="identifyTheNumberOfCards"
              width="70px"
              align="center">
            </el-table-column>
            <el-table-column label="要求" prop="conditionIdentifyNum" align="center" width="60px">
              <template slot-scope="scope">
                <span :style="{ color: scope.row.meetTheStandard == 1 ? '#07c160' : 'red' }">
                  {{ scope.row.conditionIdentifyNum }}
                </span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  getCollectionInfosBatch,
  addCollectionAnswerBatch,
  getVisitsDetail,
  selectUserDistanceTheStore,
} from '@/api/index';
import taskTips from './taskTips';
import deleteUploadImgTaskPhoto from '@/components/deleteUploadImgTaskPhoto';
import { getPosition, getTicketFun } from '@/utils/TXApiFun';
import { mapState } from 'vuex';
export default {
  name: 'abnortaskPhotoTakingmalVisit',
  components: { taskTips, deleteUploadImgTaskPhoto },
  computed: {
    ...mapState({
      userInfo: (state) => state.user.userInfo,
    }),
  },
  data() {
    return {
      formData: null,
      dataList: null,
      taskIds: [],
      visitsId: null,
      storeGroupId: '',
      objectType: '',
      insert: '',
      vanPopup: false,
      taskPhotoRecognitionResult: null,
      spanArr: [],
      pos: 0,
      mediaIds: [],
      mediaInfos: [],
      editFlag: true,
      mediaInfos: [],
    };
  },
  activated() {
    this.editFlag = true;
    if (this.formData && this.formData.collectionItemList && this.formData.collectionItemList[0]) {
      this.formData.collectionItemList[0].fileInfoList = [];
    }
    this.taskIds = this.$route.query.taskIds || [];
    this.visitsId = this.$route.query.visitsId || '';
    this.storeGroupId = this.$route.query.storeGroupId || '';
    this.objectType = this.$route.query.photoType || '';
    this.insert = this.$route.query.insert;
    // 授权
    // getTicketFun(['uploadImage']).then(() => {});
    this.toastLoading(0, '加载中...', true);
    if (this.$route.query.source == 'historicalDetails') {
      this.getVisitsDetailFun();
    } else {
      this.getDetaile();
    }
  },
  beforeRouteLeave(to, from, next) {
    if (this.$refs.taskPhoto && this.$refs.taskPhoto[0]) {
      this.$refs.taskPhoto[0].imgArr = [];
    }
    next();
  },
  watch: {},
  methods: {
    // 授权
    getTicketFunfun() {
      getTicketFun()
        .then(() => {
          getPosition()
            .then((res) => {
              let { TXisBD } = res;
              // this.lat = TXisBD.lat;
              // this.lon = TXisBD.lon;
              this.selectUserDistanceTheStoreFun(TXisBD);
            })
            .catch((error) => {
              this.$dialog.alert({
                message: error,
              });
            });
        })
        .catch(() => {});
    },
    selectUserDistanceTheStoreFun(TXisBD) {
      selectUserDistanceTheStore({
        visitsId: this.visitsId, //	Long	拜访id
        lon: TXisBD.lon, //	String	经度
        lat: TXisBD.lat, //	String	纬度
      }).then((res) => {
        if (res.code == 200) {
          this.editFlag = true;
        } else {
          this.editFlag = false;
          this.$toast(res.msg);
        }
      });
    },
    taskObjectSpanMethod({ row, column, rowIndex, columnIndex }) {
      const cellValue = row[column.property];
      if (cellValue && ['conditionIdentifyNum'].includes(column.property)) {
        const _row = this.spanArr[rowIndex]; // 合并行数
        const _col = this.spanArr[rowIndex] > 0 ? 1 : 0; // 合并的列数
        return {
          rowspan: _row,
          colspan: _col,
        };
      }
    },
    getSpanArr(data) {
      if (!data) return;
      this.spanArr = []; // tip: 后台获取完成数据后，一定要重置spanArr=[],避免出现合并混乱！！！！！
      for (let i = 0; i < data.length; i++) {
        // 当为第一行时
        if (i === 0) {
          this.spanArr.push(1);
          this.pos = 0;
        } else {
          // 判断当前值是否与上一行的【名称】相等，相等则进行合并
          if (data[i].conditionDetailId === data[i - 1].conditionDetailId) {
            this.spanArr[this.pos] += 1; // 合并单元格：合并的行数 +1
            this.spanArr.push(0); // 0代表单元格是不需要显示, 已经被合并的单元格
          } else {
            this.spanArr.push(1); // 1代表当前这行的数据需要被显示
            this.pos = i;
          }
        }
      }
    },
    getVisitsDetailFun() {
      getVisitsDetail({ visitsId: this.visitsId }).then((res) => {
        this.toastLoading().clear();
        if (res.data.sfaTaskList) {
          this.dataList = res.data.sfaTaskList.filter((val) => val.taskType == '5');
          this.formData = this.dataList[0];
          this.isEditFun();
        } else {
          this.formData = null;
        }
      });
    },
    getDetaile() {
      console.log(this.$route.query);
      getCollectionInfosBatch({
        storeCode: this.$route.query.storeCode,
        insert: this.insert,
        id: this.visitsId,
        taskIds: this.taskIds.split(','),
      }).then((res) => {
        this.toastLoading().clear();
        if (res.data && res.data.length) {
          this.dataList = res.data;
          this.formData = res.data[0];
          this.isEditFun();
        } else {
          this.formData = null;
        }
      });
    },
    isEditFun() {
      // 编辑状态下需要校验定位
      if (this.insert == 'false') this.getTicketFunfun();
    },
    openDialog(item) {
      this.vanPopup = true;
      console.log(item);
      this.getSpanArr(item.taskPhotoRecognitionResult);
      this.$nextTick(() => {
        console.log(this.spanArr);
        this.taskPhotoRecognitionResult = item.taskPhotoRecognitionResult;
      });
    },
    onSubmit() {
      this.toastLoading(0, '提交中，请稍候...', true);
      let formData = {
        storeId: this.$route.query.storeId,
        storeCode: this.$route.query.storeCode,
        storeGroupId: this.$route.query.storeGroupId,
        visitsId: this.visitsId,
        taskList: this.taskIds.split(',').map((val) => Number(val)),
        insert: this.insert,
        collectionAnswers: [],
        checkUnManage: 'N',
        deviceCode: '',
        putInCode: '',
        equipmentCode: '',
      };
      this.addCollection(formData);
    },
    syncUpload(imgArr, callback) {
      if (!imgArr.length) {
        callback && callback();
        return;
      } else {
        var item = imgArr.pop();
        if (!item.mediaId) {
          wx.uploadImage({
            localId: item.mediaFileUrl,
            isShowProgressTips: 0, // 默认为1，显示进度提示
            success: (res) => {
              this.mediaInfos.push({
                mediaId: res.serverId,
                mediaFileUrl: item.mediaFileUrl,
              });
              this.syncUpload(imgArr, callback);
            },
          });
        } else {
          this.mediaInfos.push(item);
          this.syncUpload(imgArr, callback);
        }
      }
    },
    addCollection(formData) {
      addCollectionAnswerBatch(formData).then((res) => {
        this.toastLoading().clear();
        if (res.code == 200) {
          localStorage.setItem('getRequestFlage', 'true');
          this.$router.go(-1);
        } else {
          this.$toast('提交失败，请重试');
        }
      });
    },
    onClickLeft() {
      this.$router.go(-1);
    },
  },
};
</script>
<style lang="scss">
.taskPhotoTaking {
  display: flex;
  flex-direction: column;
  width: 100%;
  height: 100%;
  overflow: hidden;
  .content {
    padding: 10px;
    flex: 1;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    padding-bottom: 46px;
    // overflow-y: auto;
    .container {
      background: #fff;
      width: 100%;
      border-radius: 6px;
      // padding: 10px;
      padding: 0 10px 10px 0px;
    }
    .formLabel {
      // margin-left: 20px;
      // border-bottom: 1px solid #f1f1f1;
    }
    .formLabel .van-cell {
      padding: 10px 0;
    }
    .formLabel .van-cell::after {
      border: 0;
    }
    .formLabel .van-field {
      border: 1px solid #f1f1f1;
      padding: 6px;
      width: 100%;
      border-radius: 4px;
      overflow: hidden;
    }
    .formLabel .van-field__control {
      padding: 0 10px;
    }
    .formLabel .formLabeltitle {
      position: absolute;
      top: 8px;
    }
    .z-cell .van-cell__title {
      font-size: 16px;
    }
    .van-f-red {
      color: red;
      width: 8px;
      display: inline-block;
      line-height: 26px;
    }
    .headline {
      font-weight: 600;
      font-size: 16px;
      position: relative;
      display: flex;
      align-items: center;
      .headlineIcon {
        display: inline-block;
        position: absolute;
        width: 3px;
        height: 60%;
        background: #3875c6;
        border-radius: 5px;
      }
      .headlineTitle {
        display: inline-block;
        padding: 0px 20px;
        background: #eef5ff;
        border-radius: 0 18px 18px 0;
        height: 36px;
        line-height: 36px;
      }
    }
  }
  .dataList {
    width: 100%;
    margin-top: 10px;
    overflow-y: auto;
    background: #fff;
    .dataItem {
      display: flex;
      // border-radius: 6px;
      flex-direction: row;
      margin-bottom: 5px;
      // padding: 10px;
      font-size: 16px;
      margin-left: 20px;
      border-bottom: 1px solid #e2e1e1;
      .itemIndex {
        display: flex;
        flex-direction: row;
      }
      .itemTop {
        flex: 1;
        overflow: hidden;
        padding-bottom: 10px;
        .itemHtml {
          overflow-x: auto;
          margin-left: 20px;
          p {
            margin: 0;
          }
        }
      }
      .itemBottom {
        display: flex;
        flex-direction: row;
      }
      .itemBottom {
        align-items: center;
        width: 60px;
        margin-left: 5px;
        img {
          width: 100%;
          height: 30px;
        }
        button {
          width: 55px;
          height: 25px;
          padding: 0;
          font-size: 12px;
        }
      }
    }
  }
}
</style>
<style lang="scss">
.taskPhotoTaking {
  .van-button--danger {
    background-color: #ee0a24 !important;
    border: 1px solid #ee0a24 !important;
  }
}
.identifyResultdialog {
  width: vw(690) !important;
  margin-top: 1vh !important;
  border-radius: 8px !important;
  font-size: vw(32) !important;
  height: 70% !important;
  display: flex;
  flex-direction: column;
  .el-dialog__headerbtn {
    width: vw(44);
    height: vw(44);
    background-color: #e1e1e1;
    border-radius: 50%;
    margin-top: -3px;
  }
  .el-dialog__body {
    flex: 1;
    overflow-y: auto;
  }
}
.table-headermd1 {
  font-size: 14px;
  text-align: center;
  position: initial;
  width: 98% !important;
  margin: 0 auto;
  border-right: 0;
  border-radius: 8px;
  th {
    color: #000;
    font-weight: bold;
  }
  td {
    color: #000;
  }
  .el-table__cell {
    padding: 6px 0 !important;
    .cell {
      padding: 0;
    }
  }
}
</style>
