<template>
  <div class="perfectStoreTask" v-if="formData">
    <van-nav-bar class="navBar" left-arrow :title="formData.taskName" @click-left="onClickLeft">
      <template #right>
        <!-- <span
          v-if="isEdit && insert == '1'"
          @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>
                  </div>
                  <!-- 操作说明图片和电话 -->
                  <taskTips
                    v-if="item.contactPhone || item.examplePhoto"
                    :contactPhone="item.contactPhone"
                    :examplePhoto="item.examplePhoto">
                  </taskTips>
                </template>
              </van-cell>
              <template
                v-if="
                  formData.taskPhotoSkuImageUrlList && formData.taskPhotoSkuImageUrlList.length
                ">
                <div
                  class="imgBox"
                  v-for="(urls, index) in formData.taskPhotoSkuImageUrlList"
                  :key="index">
                  <img
                    :src="urls.skuImageUrl"
                    @click="previewsImg(formData.taskPhotoSkuImageUrlList, index)" />
                </div>
              </template>
              <!-- <deleteUploadImg
                :imgs="item.fileInfoList"
                :storeGroupId="storeGroupId"
                :taskIds="taskIds"
                :visitsId="visitsId"
                :collectionItemId="item.collectionId"
                :putInCode="formData.putInCode"
                :photoIdentifyType="formData.photoIdentifyType"
                :pictureSource="item.pictureSource"
                :continuousShoot="item.continuousShoot"
                :insert="insert"
                :objectType="objectType"
                v-if="item.fileInfoList.length"></deleteUploadImg> -->
              <span style="font-size: 16px" v-else>暂未识别到产品照片</span>
            </div>
          </div>
        </van-form>
      </div>
      <div class="skuDeatil">
        <div class="headline" style="margin-top: 10px; justify-content: space-between">
          <div
            class="skuDeatilHeaderLeft"
            style="
              font-weight: 600;
              font-size: 16px;
              position: relative;
              display: flex;
              align-items: center;
            ">
            <span class="headlineIcon"></span>
            <span class="headlineTitle">SKU图像识别结果</span>
          </div>
          <div
            class="skuDeatilHeaderRight"
            v-if="formData.displayRewardTaskEditable"
            style="margin-right: 49px; position: relative">
            <van-button plain type="primary" @click="editTable" v-if="!editTableFlag">
              编辑
            </van-button>
            <van-button type="primary" @click="saveTable" v-if="editTableFlag">保存</van-button>
            <!-- <span style="color: #07c160" @click="editTable" v-if="!editTableFlag">编辑</span>
            <span style="color: red" @click="saveTable" v-if="editTableFlag">保存</span> -->
            <span
              style="
                position: absolute;
                font-size: 9px;
                display: inline-block;
                width: 50px;
                padding-left: 3px;
                color: #2b73cf;
              "
              >仅支持修改识别到的产品数量</span
            >
          </div>
        </div>
        <el-table
          :data="taskPhotoRecognitionResult"
          :span-method="taskObjectSpanMethod"
          border
          class="table-headermd1"
          style="width: 100%">
          <el-table-column label="序号" type="index" align="center" width="30"> </el-table-column>
          <el-table-column
            label="品类"
            prop="skuProductType"
            align="center"
            width="60"></el-table-column>
          <el-table-column label="SKU名称" prop="skuProductName" align="center">
            <template slot-scope="scope">
              <span class="tipTitle">{{ scope.row.skuProductName }}</span>
            </template>
          </el-table-column>
          <el-table-column label="排面数" prop="identifyTheNumberOfCards" align="center" width="50">
            <template slot-scope="scope">
              <span
                v-if="!editTableFlag"
                :class="{ shelfEdit: scope.row.shelfEdit == 1, identifyTheNumber: true }"
                >{{ scope.row.identifyTheNumberOfCards }}
              </span>
              <span v-else-if="!editTableFlag" class="identifyTheNumber">
                {{ scope.row.identifyTheNumberOfCards }}
              </span>
              <van-field
                v-else
                :class="{
                  shelfEdit: scope.row.shelfEdit == 1,
                  identifyTheNumber: true,
                  isEdit:
                    scope.row.identifyTheNumberOfCards > '0' && scope.row.skuProductType != '道具',
                }"
                v-model="scope.row.identifyTheNumberOfCards"
                placeholder="请输入排面数"
                type="digit"
                :disabled="
                  scope.row.identifyTheNumberOfCards == '0' || scope.row.skuProductType == '道具'
                "
                @input="onPositiveIntegerInput(scope.row, $event)"
                @blur="inputbluwl(scope.row)" />
            </template>
          </el-table-column>
          <el-table-column label="要求" prop="conditionIdentifyNum" align="center" width="50px">
            <template slot-scope="scope">
              <span
                v-if="scope.row.meetTheStandard != null"
                :style="{ color: scope.row.meetTheStandard == 1 ? '#07c160' : 'red' }">
                {{ scope.row.conditionIdentifyNum }}
              </span>
              <span v-else>{{ scope.row.conditionIdentifyNum }}</span>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="dataList" v-if="formData">
        <div class="headline" style="margin-top: 10px">
          <span class="headlineIcon"></span>
          <span class="headlineTitle">陈列任务要求</span>
        </div>
        <div class="dataItem">
          <div class="itemTop">
            <div class="itemIndex">
              <p>1、</p>
            </div>
            <div class="itemHtml" v-html="formData.displayInstructions"></div>
          </div>
          <div class="itemBottom" v-if="insert == '0'">
            <van-button round type="primary" v-if="formData.taskPhotoConditionPassed == 1"
              >通过</van-button
            >
            <van-button round type="danger" v-if="formData.taskPhotoConditionPassed == 0"
              >不通过</van-button
            >
          </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 {
  addCollectionAnswerBatch,
  getVisitsDetailPerfectStore,
  getVisitsDetailPerfectStoreByTaskId,
  updateDisplayRewardCaseSkuCount,
  buryingPoint,
} from '@/api/index';
import taskTips from '@/views/deviceWithin/taskTips';
import deleteUploadImg from '@/components/deleteUploadImgTaskPhoto';
import { ImagePreview } from 'vant';
export default {
  name: 'abnortaskPhotoTakingmalVisit',
  components: { taskTips, deleteUploadImg },
  data() {
    return {
      isEdit: true,
      formData: null,
      dataList: null,
      taskIds: [],
      visitsId: null,
      storeGroupId: '',
      objectType: '',
      insert: '',
      vanPopup: false,
      taskPhotoRecognitionResult: null,
      spanArr: [],
      editTableFlag: false,
      editCountArr: [],
    };
  },
  activated() {
    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;
    this.formData = null;
    this.editCountArr = [];
    this.editTableFlag = false;
    this.getVisitsDetailFun();
  },
  methods: {
    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() {
      this.toastLoading(0, '加载中...', true);
      getVisitsDetailPerfectStoreByTaskId({
        visitsId: this.visitsId,
        taskIdList: this.$route.query.taskId,
      }).then((res) => {
        this.toastLoading().clear();
        if (res.code == 200 && res.data && res.data.length > 0) {
          this.formData = res.data[0];
          this.taskPhotoRecognitionResult =
            JSON.parse(JSON.stringify(this.formData.taskPhotoRecognitionResult)) || [];
          this.getSpanArr(this.taskPhotoRecognitionResult);
          console.log(this.formData);
        } else {
          this.formData = null;
        }
      });
    },
    openDialog(item) {
      this.vanPopup = true;
    },
    onSubmit() {
      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: true,
        collectionAnswers: [],
        checkUnManage: 'N',
        deviceCode: '',
        putInCode: '',
        equipmentCode: '',
      };
      addCollectionAnswerBatch(formData).then((res) => {
        if (res.code == 200) {
          localStorage.setItem('getRequestFlage', 'true');
          this.$router.go(-1);
        }
      });
    },
    previewsImg(fileInfoList, index) {
      var arrimg = [];
      for (var imgi = 0; imgi < fileInfoList.length; imgi++) {
        arrimg.push(fileInfoList[imgi].skuImageUrl);
      }
      ImagePreview({
        images: arrimg,
        startPosition: index,
      });
    },
    inputbluwl(row) {
      let filteredResults = this.formData.taskPhotoRecognitionResult.filter(
        (val) => val.skuProductCode == row.skuProductCode,
      );
      if (row.rawIdentifyNum != null && row.rawIdentifyNum !== '') {
        const original = Number(filteredResults[0]?.rawIdentifyNum || '0'); //原始值
        const activeOriginal = Number(filteredResults[0]?.identifyTheNumberOfCards || '0'); //上一次修改后的值
        const current = Number(row.identifyTheNumberOfCards); //当前输入的值
        if (current < original) {
          this.$toast('排面数不能小于原始值');
          row.identifyTheNumberOfCards = String(activeOriginal);
          const existingIndex = this.editCountArr.findIndex(
            (item) => item.skuProductCode === row.skuProductCode,
          );
          if (existingIndex >= 0) {
            this.editCountArr.splice(existingIndex, 1);
          }
        } else {
          const editCount = current - activeOriginal; //本次修改的值
          if (editCount === 0) {
            const existingIndex = this.editCountArr.findIndex(
              (item) => item.skuProductCode === row.skuProductCode,
            );
            if (existingIndex >= 0) {
              this.editCountArr.splice(existingIndex, 1);
            }
          } else {
            const existingIndex = this.editCountArr.findIndex(
              (item) => item.skuProductCode === row.skuProductCode,
            );
            if (existingIndex >= 0) {
              this.editCountArr[existingIndex].editCount = editCount;
            } else {
              this.editCountArr.push({
                taskId: row.taskId, //	Long	任务id
                visitId: row.visitId, //	Long	拜访id
                skuProductCode: row.skuProductCode, //	String	产品code
                editCount,
              });
            }
          }
        }
      } else {
        this.$toast('排面数不能为空');
        row.identifyTheNumberOfCards = filteredResults[0]?.identifyTheNumberOfCards;
      }
    },
    onPositiveIntegerInput(row, value) {
      if (value == null) {
        row.identifyTheNumberOfCards = '';
        return;
      }
      let sanitized = String(value).replace(/[^\d]/g, '');
      if (sanitized !== '') {
        sanitized = sanitized.replace(/^0+/, '');
        if (sanitized === '') {
          sanitized = '0';
        }
      }
      row.identifyTheNumberOfCards = sanitized;
    },
    editTable() {
      this.editTableFlag = true;
    },
    saveTable() {
      console.log(this.editCountArr);
      if (this.editCountArr.length == 0) {
        // this.$toast('请至少修改一项排面数');
      } else {
        updateDisplayRewardCaseSkuCount(this.editCountArr).then((res) => {
          if (res.code == 200) {
            this.$toast('修改成功');
            buryingPoint({
              systemModel: '拜访页',
              buryingPointType: 11,
              buryingPointValue: `${this.$route.query.storeName}(${this.$route.query.storeCode})`,
              buryingPointName: '修改排面数',
              buryingPointPosition: '拜访页',
            });
            this.getVisitsDetailFun();
          } else {
            this.$toast(res.message || '修改失败');
          }
        });
      }
      this.editTableFlag = false;
    },
    onClickLeft() {
      this.$router.go(-1);
    },
  },
};
</script>
<style lang="scss" scoped>
.perfectStoreTask {
  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;
    .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: 10px;
      // padding: 10px;
      font-size: 16px;
      margin-left: 20px;
      border-bottom: 1px solid #e2e1e1;
      .itemIndex {
      }
      .itemTop {
        flex: 1;
        overflow: hidden;
        padding-bottom: 10px;
        .itemHtml {
          overflow-x: auto;
        }
      }
      .itemTop,
      .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;
        }
      }
    }
  }
  .tableTitle {
    padding: 10px 0;
    font-size: 16px;
    font-weight: bold;
    background: #f5f5f5;
    margin: 15px 0;
  }
  .imgBox {
    width: 22%;
    height: 80px;
    position: relative;
    display: inline-block;
    border-radius: 6px;
    overflow: hidden;
    margin: 3px 1.5%;
    img {
      width: 100%;
      height: 100%;
    }
  }
}
</style>
<style lang="scss">
.perfectStoreTask {
  .van-button--danger {
    background-color: #ee0a24 !important;
    border: 1px solid #ee0a24 !important;
  }
  .table-headermd1 {
    .el-table__cell {
      height: 50px !important;
      .van-field {
        padding: 0 !important;
      }
      .van-field__control {
        height: 32px;
        text-align: center;
      }
    }
  }
  .shelfEdit {
    height: 100%;
    color: #036bf3;
    .van-field__body {
      height: 100%;
    }
    input {
      height: 100%;
      color: #036bf3;
    }
  }
  .identifyTheNumber {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 100%;
  }
  .isEdit {
    border: 1px solid #609de8;
  }
  .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: 0 !important;
      .cell {
        height: 100%;
        padding: 0;
        display: flex;
        align-items: center;
        justify-content: center;
      }
    }
  }
  .skuDeatil {
    width: 100%;
    margin-top: 10px;
    background: #fff;
    border-radius: 6px;
    .table-headermd1 {
      font-size: 14px;
      text-align: center;
      position: initial;
      width: 98% !important;
      margin: 0 auto;
      border-right: 0;
      border-radius: 8px;
      margin-top: 10px;
      th {
        color: #000;
        font-weight: bold;
      }
      td {
        color: #000;
      }
      .el-table__cell {
        padding: 0 !important;
        .cell {
          height: 100%;
          padding: 0;
        }
      }
    }
    .table-headermd1 th.el-table__cell {
      background-color: #f5f5f5;
    }
  }
}
.el-table::before {
  height: 0;
}
.skuDeatilHeaderRight {
  button {
    // width: 120px;
    height: 36px;
    border-radius: 18px;
  }
  .van-button--primary {
    background-color: #2b73cf;
    border-color: #2b73cf;
  }
  .van-button--primary.van-button--plain {
    color: #3875c6;
    border-color: #dcdfe6;
    background-color: rgba(217, 233, 255, 1);
  }
}
</style>
