<template>
  <div class="app-container setting-main">
    <div class="app-container-search main-radius">
      <h1 style="margin: 0;">标识详情</h1>
    </div>
    <div class="app-container-search main-bgcolor main-radius setting-container">
      <div class="setting-title flex-jcenter">
        <div class="">基本信息</div>
      </div>
      <el-row style="margin-bottom: 20px;">
        <el-col :span="24" class="setting-info">
          <span>标识二维码：{{info.identityCode}}</span>
          <el-button style="padding: 0;" type="text" @click="watchCode">查看二维码</el-button>
        </el-col>
      </el-row>
      <el-row style="margin-bottom: 20px;">
        <el-col :span="8"><span>关联商品：{{info.goodsName}}</span></el-col>
        <el-col :span="8"><span>所属批次：{{info.batchId}}</span></el-col>
        <el-col :span="8"><span>所属商户：{{info.belongBusinessName}}</span></el-col>
      </el-row>
      <el-row>
        <el-col :span="8" v-if="info.verfiyCode"><span>验证码：{{info.verfiyCode}}</span></el-col>
        <!-- <el-col :span="8"><span>店铺链接：</span></el-col> -->
        <!-- <el-col :span="8"><span>父标识：</span></el-col> -->
      </el-row>
    </div>
    <div class="app-container-search main-bgcolor main-radius setting-container">
      <div class="setting-title flex-jcenter">
        <div class="">识别信息</div>
      </div>
      <el-row>
        <el-col :span="6"><span>识别次数：{{ identify.total?identify.total:'-' }}</span></el-col>
      </el-row>
      <el-row style="margin-top: 10px;">
        <el-col :span="6"><span>首次识别时间：{{ identify.scanTime?parseTime( identify.scanTime ):"-" }}</span></el-col>
        <el-col :span="6"><span>首次识别地点：{{ identify.scanLocation?identify.scanLocation:'-' }}</span></el-col>
        <el-col :span="6"><span>首次识别手机型号：{{ identify.mobileSystemInfo.brand?`${identify.mobileSystemInfo.brand} ${identify.mobileSystemInfo.model}`:'-' }}</span></el-col>
        <el-col :span="6"><span>首次识别操作系统版本：{{ identify.mobileSystemInfo.system?identify.mobileSystemInfo.system:'-' }}</span></el-col>
      </el-row>
    </div>
    <div class="app-container-search main-bgcolor main-radius setting-container">
      <div class="setting-title flex-jcenter">
        <div class="">识别记录（展示最近10条记录）</div>
      </div>
      <!-- 列表 -->
      <el-table v-loading="loading" :data="list">
        <el-table-column label="序号" type="index" width="60" />
        <el-table-column label="扫码地点" prop="scanLocation" />
        <el-table-column label="手机型号" prop="brand">
          <template v-slot="{ row }">
            <span>{{ row.mobileSystemInfo.brand }} {{ row.mobileSystemInfo.model }}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作系统版本" prop="system">
          <template v-slot="{ row }">
            <span>{{ row.mobileSystemInfo.system }}</span>
          </template>
        </el-table-column>
        <el-table-column label="来源" prop="source">
          <template v-slot="{ row }">
            <span>{{ row.mobileSystemInfo.type == "h5" ? "手机浏览器" : "小程序" }}</span>
          </template>
        </el-table-column>
        <el-table-column label="扫码时间" prop="scanTime" >
          <template v-slot="{ row }">
            <span>{{ parseTime(row.scanTime) }}</span>
          </template>
        </el-table-column>
        <div slot="empty">
          <EmptyTable />
        </div>
      </el-table>
    </div>

    <el-dialog
      title="标识二维码"
      :visible.sync="dialogVisible"
      :width="'300px'">
      <div class="flex-allcenter codeId" v-if="dialogVisible"></div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import EmptyTable from '@/components/EmptyTable'
  import {getCode} from '@/api/identity/code';
  import { getFirstScanInfoByUrlAndNumber , getScanLocationAndTimeByUrl } from '@/api/identity/diversionRecord';
  import { getDictDataListByTypeList, addData } from "@/api/system/dict/data";
  import { CommonStatusEnum } from '@/utils/constants'

  import QRCode from "qrcodejs2";
  import MobileDetect from 'mobile-detect';
  import { arrModal } from '@/utils/model';
  import { getModel } from '@/utils/mobileModel';

  export default{
    components: {
      EmptyTable,
    },
    data() {
      return{
        info: {},
        identify: {},
        queryParams: {
          pageNo: 1,
          pageSize: 10,
        },
        total: 0,
        loading: false,
        list: [],
        dialogVisible: false,
        brandTypeList: [],
        unkownBrand: {},
      }
    },
    created() {
      let id = this.$route.query.id;
      this.getDate(id);
    },
    methods:{
      async getDate(id) {
        let res = await getCode(id);
        this.info = res.data;
        this.identify = {};
        if (res.data) {
          const { data: brandTypeData } = await getDictDataListByTypeList({ typeList: "brand_type" });
          this.brandTypeList = brandTypeData;

          getFirstScanInfoByUrlAndNumber({ identityUrl: res.data.identityCode }).then(async ({ data }) => {
            if(data) {
              this.identify = data;
              const brandSet = new Set();
              const modelMap = {};

              data.mobileSystemInfo = JSON.parse(data.mobileSystemInfo);
              if (data.mobileSystemInfo.type == "h5") {
                if (data.mobileSystemInfo.brand != "UnknownTablet") {
                  brandSet.add(data.mobileSystemInfo.brand);
                }
              }

              let resf = await getScanLocationAndTimeByUrl({identityUrl: res.data.identityCode});
              const sacnPageList = resf.data.map(item => {
                item.mobileSystemInfo = JSON.parse(item.mobileSystemInfo);
                if (item.mobileSystemInfo.type == "h5") {
                  if (item.mobileSystemInfo.brand != "UnknownTablet") {
                    brandSet.add(item.mobileSystemInfo.brand);
                  }
                }
                return item;
              });

              if (brandSet.size > 0) {
                for (let brand of brandSet) {
                  modelMap[brand] = [];
                }
                // 请求品牌对应的手机型号
                const { data: dictData } = await getDictDataListByTypeList({ typeList: [...brandSet].join(",") });
                dictData.map(dict => {
                  modelMap[dict.dictType].push({
                    label: dict.label,
                    value: dict.value,
                  });
                });
              }

              if (data.mobileSystemInfo.type == "h5") {
                if (data.mobileSystemInfo.brand != "UnknownTablet") {
                  let brand = data.mobileSystemInfo.brand;
                  let model = data.mobileSystemInfo.model;
                  const brandInfo = this.getBrandFromBrandTypeList(brand);
                  if (brandInfo) {
                    // 将品牌转换为自定义值
                    brand = brandInfo.brandLabel;
                    // 尝试将型号转换为自定义值
                    const modelList = modelMap[brandInfo.brandValue];
                    if (modelList) {
                      const modelInfo = modelList.find(item => item.value == model.trim());
                      if (modelInfo) {
                        model = modelInfo.label;
                      }
                    }
                  }

                  this.identify.mobileSystemInfo = {
                    ...data.mobileSystemInfo,
                    brand,
                    model,
                  }
                } else {
                  this.identify.mobileSystemInfo = {
                    ...data.mobileSystemInfo,
                    brand: "未知品牌",
                    model,
                  }
                }
              } else {
                // 非h5 直接赋值
                this.identify.mobileSystemInfo = data.mobileSystemInfo;
              }
              this.list = sacnPageList.map(record => {
                if (record.mobileSystemInfo.type == "h5") {
                  if (record.mobileSystemInfo.brand != "UnknownTablet") {
                    let brand = record.mobileSystemInfo.brand;
                    let model = record.mobileSystemInfo.model;
                    const brandInfo = this.getBrandFromBrandTypeList(brand);
                    if (brandInfo) {
                      // 将品牌转换为自定义值
                      brand = brandInfo.brandLabel;
                      // 尝试将型号转换为自定义值
                      const modelList = modelMap[brandInfo.brandValue];
                      if (modelList) {
                        const modelInfo = modelList.find(item => item.value == model.trim());
                        if (modelInfo) {
                          model = modelInfo.label;
                        }
                      }
                    }

                    record.mobileSystemInfo = {
                      ...record.mobileSystemInfo,
                      brand,
                      model,
                    }
                  } else {
                    record.mobileSystemInfo.brand = "未知品牌";
                  }
                }
                return record;
              });
            }
          });
        }
      },
      getBrandFromBrandTypeList(brand) {
        for (let brandType of this.brandTypeList) {
          if (brand == brandType.value) {
            return {
              brandLabel: brandType.label,
              brandValue: brandType.value,
            };
          }
        }
        return null;
      },
      getBrandFromUserAgent(record) {
        const userAgent = record.mobileSystemInfo.userAgent;
        // 找到品牌的开始位置 将Gecko) 后面的内容取出来
        const brandStartIndex = userAgent.indexOf('Gecko) ');
        if (brandStartIndex > 0) {
          const brandString = userAgent.substring(brandStartIndex + 8);
          const brandInfoList = brandString.split('/');
          if (brandInfoList.length > 0) {
            for (let brandType of this.brandTypeList) {
              for (let brand of brandInfoList) {
                if (brand.indexOf(brandType.value) >= 0) {
                  return {
                    brandLabel: brandType.label,
                    brandValue: brandType.value,
                  };
                }
              }
            }
          }
          this.unkownBrand[record.id] = brandString;
        } else {
          this.unkownBrand[record.id] = userAgent;
        }
        return null;
      },
      // 从userAgent中尝试获取手机型号
      getModelFromUserAgent(userAgent) {
        // 先找到Build/的位置
        const buildStrIndex = userAgent.indexOf('Build/');
        if (buildStrIndex > 0) {
          const modelStartIndex = userAgent.lastIndexOf(" ", buildStrIndex - 2);
          if (modelStartIndex > 0) {
            return userAgent.substring(modelStartIndex + 1, buildStrIndex - 1);
          }
        }
        return null;
      },
      watchCode() {
        this.dialogVisible = true;
        setTimeout(()=>{
          this.generateQRCode('.codeId',this.info.identityCode);
        },1000);
      },
      // 生成二维码
      generateQRCode(classId,value) {
        new QRCode(document.querySelector(classId), {
          text: value,
          width: 240,
          height: 240,
          colorDark: "#000000",
          colorLight: "#ffffff",
          correctLevel: QRCode.CorrectLevel.H
        })
      },
    },
  }
</script>

<style>
  .setting-info{
    margin-bottom: 20px;
  }
  .setting-info:last-child{
    margin-bottom: 0px;
  }
</style>
