<template>
  <div v-loading="loading" :element-loading-text="loadingText">
    <el-steps :active="1" align-center simple>
      <el-step style="cursor: pointer;" @click.native="active = 0" title="上传质保单" icon="el-icon-upload" />
      <el-step style="cursor: pointer;" @click.native="active = 1" title="质保单处理" icon="el-icon-edit" />
      <el-step style="cursor: pointer;" @click.native="active = 2" title="质保单审核" icon="el-icon-check" />
    </el-steps>
      <div v-if="active === 0" style="padding: 30px;">
        <file-upload v-model="uploadQualityCertificateForm.qualityCertificate" />
      </div>

      <div v-if="active === 1">
        <el-row>
          <el-alert title="质保单处理" type="info" />
        </el-row>
        
        <!-- 提取质保单信息,选择使用ocr还是使用大模型 -->
        <el-row :gutter="20">
          <!-- <el-col :span="12">
            <div style="height: 300px; border: 1px solid #ccc; border-radius: 10px; padding: 20px; cursor: pointer;" @click="handleOcr">
              OCR识别
              <img :src="ocrImage" alt="ocr" style="width: 100%; height: 100%;" />
            </div>
          </el-col> -->
          <el-col :span="24">
            <div style="height: 300px; border: 1px solid #ccc; border-radius: 10px; padding: 20px; cursor: pointer; display: flex; justify-content: center; align-items: center;" @click="handleModel">
              <img :src="modelImage" alt="model" style="height: 100%;" />
            </div>
          </el-col>
        </el-row>
      </div>

      <div v-if="active === 2">
        <div v-if="resultDiff">
          <merger :info="info" :old-result="oldResult" :new-result="newResult" @confirm="handleMergerConfirm" />
        </div>
        <div v-else>
          <el-row>
            <el-alert title="请核对识别结果是否正确" type="success" />
          </el-row>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-table :data="newResult" style="width: 100%">
                <el-table-column prop="attrKey" label="属性名称" />
                <el-table-column prop="attrValue" label="属性值" />
              </el-table>
            </el-col>
            <el-col :span="12">
              <div>
                <img style="width: 100%; height: 100%;" :src="file.url" alt="">
              </div>
            </el-col>
          </el-row>
          <el-button type="primary" @click="handleConfirm">确认</el-button>
        </div>
      </div>
  </div>
</template>

<script>
import FileUpload from '@/components/FileUpload'
import { listByIds } from '@/api/system/oss'
import { updatePurchasePlanDetail } from '@/api/wms/purchasePlanDetail'
import { recognizeText, recognizeBomByModel } from '@/api/system/ocr'
import { listBomItem } from '@/api/wms/bomItem'
import { getRawMaterial } from '@/api/wms/rawMaterial'
import Merger from './merger.vue'

import modelImage from '@/assets/images/model.png'
import ocrImage from '@/assets/images/ocr.png'

const so = {
  annex: {
    loading: '正在保存质保单',
    handler: async (vm, newVal) => {
      return await updatePurchasePlanDetail({
        ...vm.info,
        annex: newVal
      })
    }
  },
  ocr: {
    loading: '等待ocr识别结果',
    handler: async (vm) => {
      const text = await recognizeText({ imgUrl: vm.file.url })
      return text;
    }
  },
  model: {
    loading: '等待大模型识别结果',
    handler: async (vm) => {
      const res = await recognizeBomByModel({ imageUrl: vm.file.url })
      vm.newResult = res.data.attributes;
      vm.$modal.msgSuccess("识别成功");
      return res;
    }
  },
  bom: {
    loading: '正在处理BOM'
  },
  oss: {
    loading: '正在获取质保单',
    handler: async (vm, newVal) => {
      const res = await listByIds(newVal)
      vm.file = res.data[0];
      vm.active = 1;
      return res.data[0];
    }
  },
  old: {
    loading: '正在获取历史质保单',
    handler: async (vm, newVal) => {
      // 查询对应的bomId
      const res = await getRawMaterial(vm.info.rawMaterialId)
      const bomId = res.data.bomId;
      const bomItemRes = await listBomItem({
        bomId,
      })
      vm.oldResult = bomItemRes.rows;
      return bomItemRes.rows;
    }
  }
}

// 原子操作, 用于细化的进度展示, 无论其同步还是异步一律视作异步函数执行, 并返回一个Promise
const atoms = {

}

export default {
  name: 'QualityCerticate',
  components: {
    FileUpload,
    Merger
  },
  props: {
    info: {
      type: Object,
      default: () => ({})
    }
  },
  watch: {
    info: {
      handler(newVal) {
        this.active = 0;
        if (newVal.annex) {
          this.uploadQualityCertificateForm.qualityCertificate = newVal.annex;
        } else {
          this.uploadQualityCertificateForm.qualityCertificate = undefined;
        }
      },
      deep: true,
      immediate: true
    },
    'uploadQualityCertificateForm.qualityCertificate': {
      handler(newVal) {
        if (newVal) {
          this.loadingMethod('oss')  
        }
        this.loadingMethod('annex')
      },
      immediate: true
    }
  },
  data() {
    return {
      uploadQualityCertificateForm: {
        qualityCertificate: undefined,
        qualityCertificateType: undefined,
      },
      active: 0,
      file: undefined,
      loading: false,
      loadingText: '加载中...',
      resultDiff: true,
      oldResult: [],
      newResult: [],
      modelImage,
      ocrImage,
    }
  },
  methods: {
    handleOcr() {
      this.loadingMethod('ocr', (res) => {
        this.loadingMethod('old').then(() => {
          this.handleCompareResult()
          this.active = 2;
        })
      })
    },
    handleModel() {
      this.loadingMethod('model', async (res) => {
        await this.loadingMethod('old')
        console.log(this);
        this.handleCompareResult()
        this.active = 2;
      })
      
    },
    async handleConfirm() {
      // 变更状态
      this.active = 3;
      this.$emit('confirm')
    },
    handleMergerConfirm(res) {
      if (res.status === 'start') {
        this.loading = true;
        this.loadingText = '正在处理产品BOM';
      } else if (res.status === 'success') {
        this.loading = false;
        this.active = 3;
        this.$emit('confirm')
      } else if (res.status === 'error') {
        this.loading = false;
        this.$modal.msgError('质保单处理失败');
      }
    },
    async loadingMethod(key, fn) {
      this.loading = true;
      this.loadingText = so[key].loading;
      try {
        const res = await so[key].handler(this, this.uploadQualityCertificateForm.qualityCertificate)
        fn && await fn(res)
        return res;
      } catch {
        this.$modal.msgError('操作失败');
      } finally {
        this.loading = false;
      }
    },
    // 比较新旧result是否一致
    handleCompareResult() {
      // 先检查新旧result是否一致
      if (this.oldResult.length !== this.newResult.length) {
        this.resultDiff = true;
        return;
      }
      // 比较新旧result是否一致
      for (let i = 0; i < this.oldResult.length; i++) {
        if (this.oldResult[i].attrKey !== this.newResult[i].attrKey || this.oldResult[i].attrValue !== this.newResult[i].attrValue) {
          this.resultDiff = true;
          return;
        }
      }
      this.resultDiff = false;
    }
  }
}
</script>

<style scoped>
.el-row {
  margin-bottom: 20px;
  margin-top: 20px;
}
</style>