<template>
  <div class="app-container">
    <div class="app-container-search main-bgcolor main-radius">
      <h1 class="">查询标识</h1>
      <br />
      <!-- 搜索工作栏 -->
      <Bound
      ref="searchForm"
        :searchFormParam="{ queryParams, dataSource }"
        :showSearch.sync="showSearch"
        @handleQuery="handleQuery"
        @resetQuery="resetQuery"
      ></Bound>
    </div>

    <!-- 列表 -->
    <div class="app-container-search main-bgcolor main-radius">
      <h2>标识列表</h2>
      <br/>
      <el-table v-loading="loading" :data="list">
        <el-table-column label="商户名称" align="center" prop="belongBusinessName" />
        <el-table-column label="批次号" align="center" prop="batchId" >
          <template slot-scope="{ row }">
            <el-tooltip class="item" effect="dark" :content="row.batchId" placement="top">
              <div class="table-column">
                <span class="more-width-20">{{row.batchId}}</span>
                <el-button type="text" icon="el-icon-copy-document" @click.stop="copyContent(row.batchId)"></el-button>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center" prop="goodsName" />
        <!-- 码值 目前默认编码 -->
        <el-table-column label="码值" align="center" prop="identityCode" >
          <template slot-scope="{ row }">
            <el-tooltip class="item" effect="dark" :content="row.identityCode" placement="top">
              <div class="table-column">
                <span class="more-width-20">{{row.identityCode}}</span>
                <el-button type="text" icon="el-icon-copy-document" @click.stop="copyContent(row.identityCode)"></el-button>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="二维码" align="center" prop="id" >
          <template v-slot="{row}">
            <div class="flex-allcenter" :class="'id'+row.id"></div>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template v-slot="{ row }">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="toSetting(row,'/code/setting/codeDetail')"
                    >详情</el-button>
            <el-button size="mini" type="text" @click="openSelectLanguage(row.batchId, row.identityCode)"
                    >预览</el-button>
          </template>
        </el-table-column>
        <div slot="empty">
          <EmptyBound />
        </div>
      </el-table>
      <!-- 分页组件 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>
    </div>
    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="500px" v-dialogDrag append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="生码记录id" prop="generateRecordId">
          <el-input v-model="form.generateRecordId" placeholder="请输入生码记录id" />
        </el-form-item>
        <el-form-item label="二维码url " prop="identityCode">
          <el-input v-model="form.identityCode" placeholder="请输入二维码url " />
        </el-form-item>
        <el-form-item label="校验码（明暗码需要）" prop="verfiyCode">
          <el-input v-model="form.verfiyCode" placeholder="请输入校验码（明暗码需要）" />
        </el-form-item>
        <el-form-item label="码规则id" prop="ruleId">
          <el-input v-model="form.ruleId" placeholder="请输入码规则id" />
        </el-form-item>
        <el-form-item label="码规则" prop="codeRuleFormat">
          <el-input v-model="form.codeRuleFormat" placeholder="请输入码规则" />
        </el-form-item>
        <el-form-item label="码类型 0普通码 1明暗码" prop="codeType">
          <el-select v-model="form.codeType" placeholder="请选择码类型 0普通码 1明暗码">
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>
        <el-form-item label="字符长度" prop="charLength">
          <el-input v-model="form.charLength" placeholder="请输入字符长度" />
        </el-form-item>
        <el-form-item label="字符类型 0纯数字  1纯字母  2混合类型" prop="charType">
          <el-select v-model="form.charType" placeholder="请选择字符类型 0纯数字  1纯字母  2混合类型">
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>
        <el-form-item label="相关批次ID" prop="batchId">
          <el-input v-model="form.batchId" placeholder="请输入相关批次ID" />
        </el-form-item>
        <el-form-item label="批次类型： 0：采收批次" prop="batchType">
          <el-select v-model="form.batchType" placeholder="请选择批次类型： 0：采收批次">
            <el-option label="请选择字典生成" value="" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品id" prop="goodsId">
          <el-input v-model="form.goodsId" placeholder="请输入商品id" />
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsName">
          <el-input v-model="form.goodsName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="经销商名称" prop="dealerName">
          <el-input v-model="form.dealerName" placeholder="请输入经销商名称" />
        </el-form-item>
        <el-form-item label="经销商id" prop="dealerId">
          <el-input v-model="form.dealerId" placeholder="请输入经销商id" />
        </el-form-item>
        <el-form-item label="所属商户id" prop="belongBusinessId">
          <el-input v-model="form.belongBusinessId" placeholder="请输入所属商户id" />
        </el-form-item>
        <el-form-item label="所属商户名称" prop="belongBusinessName">
          <el-input v-model="form.belongBusinessName" placeholder="请输入所属商户名称" />
        </el-form-item>
        <el-form-item label="扫码次数统计" prop="scanCount">
          <el-input v-model="form.scanCount" placeholder="请输入扫码次数统计" />
        </el-form-item>
        <el-form-item label="最多可追溯统计次数" prop="limitCount">
          <el-input v-model="form.limitCount" placeholder="请输入最多可追溯统计次数" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 选择语言 -->
    <el-dialog
      title="选择语言"
      :visible.sync="selectLanguage"
      width="400px"
      :before-close="closeSelectLanguage"
      append-to-body
    >
      <el-form :model="languageForm" :rules="languageRules" ref="languageFormRef" label-width="80px">
        <el-form-item label="语言" prop="languageTypeId">
          <el-select v-model="languageForm.languageTypeId" placeholder="请选择语言">
            <el-option v-for="item in languageList" :key="item.id" :label="item.name" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeSelectLanguage">取消</el-button>
        <el-button type="primary" @click="handlePreview">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      v-if="dialogPreview"
      title="小程序预览"
      :visible.sync="dialogPreview"
      width="415px"
      heigth="950px"
      class="preview-dialog"
      close-on-click-modal
    >
      <div class="preview-dialog-content">
        <appPreview :info="previewInfo"></appPreview>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import EmptyBound from '@/components/EmptyTable';
import Bound from '@/components/Customer/SearchForm';
import appPreview from '@/components/Customer/appPreview';

import { createCode, updateCode, deleteCode, getCode, getCodePage, exportCodeExcel } from "@/api/identity/code";
import {
  previewLinkConfig
} from "@/api/production/harvestBatch";
import { getFirstScanInfoByUrl } from "@/api/identity/businessRule";
import { getAllLanguageType } from "@/api/system/languageType";

import QRCode from "qrcodejs2"

export default {
  name: "Code",
  components: {
    Bound,
    EmptyBound,
    appPreview,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 标识码列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        generateRecordId: null,
        identityCode: null,
        verfiyCode: null,
        ruleId: null,
        codeRuleFormat: null,
        codeType: null,
        charLength: null,
        charType: null,
        batchId: null,
        batchType: null,
        goodsId: null,
        goodsName: null,
        dealerName: null,
        dealerId: null,
        belongBusinessId: null,
        belongBusinessName: null,
        createTime: [],
        scanCount: null,
        limitCount: null,
        state: null,
      },
      dataSource: [
       {
        key: 'identityCode', //码值
        itemType: 'input',
        label: '码值',
        placeholder: '请输入',
        onEnterKeyUp: this.handleQuery,
      },
     ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        generateRecordId: [{ required: true, message: "生码记录id不能为空", trigger: "blur" }],
        identityCode: [{ required: true, message: "二维码url 不能为空", trigger: "blur" }],
        ruleId: [{ required: true, message: "码规则id不能为空", trigger: "blur" }],
        codeRuleFormat: [{ required: true, message: "码规则不能为空", trigger: "blur" }],
        codeType: [{ required: true, message: "码类型 0普通码 1明暗码不能为空", trigger: "change" }],
        charLength: [{ required: true, message: "字符长度不能为空", trigger: "blur" }],
        charType: [{ required: true, message: "字符类型 0纯数字  1纯字母  2混合类型不能为空", trigger: "change" }],
        batchId: [{ required: true, message: "相关批次ID不能为空", trigger: "blur" }],
        batchType: [{ required: true, message: "批次类型： 0：采收批次不能为空", trigger: "change" }],
        belongBusinessId: [{ required: true, message: "所属商户id不能为空", trigger: "blur" }],
        belongBusinessName: [{ required: true, message: "所属商户名称不能为空", trigger: "blur" }],
      },

      previewInfo: {},
      dialogPreview: false,
      // 选择语言弹窗
      selectLanguage: false,
      languageList: [],
      languageForm: {},
      languageRules: {
        languageTypeId: [{ required: true, message: "请选择语言", trigger: "blur" }],
      },
      selectHarvestBatchCode: '',
      identityUrl: '',
    };
  },

  created() {
    this.getList();
  },

  methods: {
    filterText(blockState){
      switch(blockState){
        case 0:
          return '未上传'
        case 1:
          return '已上传'
        case 2:
          return '冻结'
        default :
          break;
      }
    },
    toSetting(row,path){
      this.$router.push({
        path,
        query:{
          id: row.id,
        }
      })
    },
    // 生成二维码
    generateQRCode(classId,value) {
      console.log(value);
      new QRCode(document.querySelector(classId), {
        text: value,
        width: 80,
        height: 80,
        colorDark: "#000000",
        colorLight: "#ffffff",
        correctLevel: QRCode.CorrectLevel.H
      })
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      this.list = [];
      if(!this.queryParams.identityCode){
        this.loading = false;
        return;
      }
      // 执行查询
      getCodePage(this.queryParams).then(response => {
        response.data.list.map(item=>{
          item.id = String(item.id);
        });
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
        setTimeout(()=>{
          if(this.total>0){
            this.list.map(item=>{
              this.generateQRCode('.id'+item.id,item.identityCode);
            });
          }
        },1000);
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        generateRecordId: undefined,
        identityCode: undefined,
        verfiyCode: undefined,
        ruleId: undefined,
        codeRuleFormat: undefined,
        codeType: undefined,
        charLength: undefined,
        charType: undefined,
        batchId: undefined,
        batchType: undefined,
        goodsId: undefined,
        goodsName: undefined,
        dealerName: undefined,
        dealerId: undefined,
        belongBusinessId: undefined,
        belongBusinessName: undefined,
        scanCount: undefined,
        limitCount: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm", "searchForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加标识码";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getCode(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改标识码";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateCode(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createCode(this.form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除标识码编号为"' + id + '"的数据项?').then(function() {
          return deleteCode(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有标识码数据项?').then(() => {
          this.exportLoading = true;
          return exportCodeExcel(params);
        }).then(response => {
          this.$download.excel(response, '标识码.xls');
          this.exportLoading = false;
        }).catch(() => {});
    },

    openSelectLanguage(harvestBatchId, identityUrl) {
      this.resetForm("languageFormRef");
      this.selectLanguage = true;
      this.selectHarvestBatchCode = harvestBatchId;
      this.identityUrl = identityUrl;
      getAllLanguageType().then(({ data }) => {
        this.languageList = data;
      });
    },

    closeSelectLanguage() {
      this.selectLanguage = false;
    },

    // 预览小程序效果
    async handlePreview() {
      // 采收信息
      let { data } = await previewLinkConfig({ harvestBatchId: this.selectHarvestBatchCode, languageTypeId: this.languageForm.languageTypeId });
      this.dialogPreview = true;
      this.$nextTick(() => {
        const previewInfo = data.uniTemplate;
        // 取出环节信息
        const linkList = data.linkInfos;
        previewInfo.templateItemList.forEach((item, index) => {
          const linkInfo = linkList[index];
          if (linkInfo) {
            item.name = linkInfo.linkName;
          }
        });

        previewInfo.templateItemList = previewInfo.templateItemList.filter(item => item.name);

        this.previewInfo = previewInfo;
      });
    },

  }
};
</script>
<style scoped lang="scss">
  .identityCode{
    max-width: 200px;
  }

  .preview-dialog {
    :deep(.el-dialog__headerbtn) {
      top: 10px;
    }
    :deep(.el-dialog__body) {
      padding: 0px 20px 10px 20px;
    }

    .preview-dialog-content {
      width: 375px;
      position: relative;
    }
  }
</style>
