<template>
  <div class="app-container">
    <div class="app-container-search main-bgcolor main-radius">
      <h1 class="">采收批次</h1>
      <br />
      <!-- 搜索工作栏 -->
      <SearchForm
        ref="searchForm"
        :searchFormParam="searchFormParam"
        :showSearch.sync="showSearch"
        @handleQuery="handleQuery"
        @resetQuery="resetQuery"
      ></SearchForm>
    </div>

    <div class="app-container-list main-bgcolor main-radius shopping">
      <div class="shopping-top">
        <div class="shopping-title">采收批次列表</div>
        <div>
          <el-button size="mini" type="text" @click="initializeConfig()" v-hasPermi="['product:harvest-batch:init-config']">初始化批次配置</el-button>
        </div>
      </div>
      <!-- 列表 -->
      <el-table v-loading="loading" :data="list">
        <el-table-column type="selection" width="55"/>
        <el-table-column label="编号" align="center" type="index" width="80" >
          <template v-slot="{ $index }">
            <span>{{($index+1)+ (searchFormParam.queryParams.pageNo-1)*searchFormParam.queryParams.pageSize }}</span>
          </template>
        </el-table-column>
        <el-table-column label="采收批次编码" align="center" prop="harvestBatchId" >
          <template slot-scope="{ row }">
            <el-tooltip class="item" effect="dark" :content="row.harvestBatchId" placement="top">
              <div class="flex-acenter">
                <span class="more-width-20">{{row.harvestBatchId}}</span>
                <el-button type="text" icon="el-icon-copy-document" @click.stop="copyContent(row.harvestBatchId)"></el-button>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="入库单号" align="center" prop="harvestId" >
          <template slot-scope="{ row }">
            <el-tooltip class="item" effect="dark" :content="row.harvestId" placement="top">
              <div class="flex-acenter">
                <span class="more-width-20">{{row.harvestId}}</span>
                <el-button type="text" icon="el-icon-copy-document" @click.stop="copyContent(row.harvestId)"></el-button>
              </div>
            </el-tooltip>
          </template>
        </el-table-column>
        <el-table-column label="入库日期" align="center" prop="harvestDate" >
          <template v-slot="{row}">
            <span>{{parseTime(row.harvestDate,'{y}-{m}-{d}')}}</span>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" align="center" prop="goodsName" >
          <template v-slot="{row}">
            <div class="flex-allcenter w100">
              <span class="more-width-20">{{row.goodsName}}</span>
              <el-button type="text" icon="el-icon-copy-document" @click.stop="copyContent(row.goodsName)"></el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="所属商户" align="center" prop="belongBusinessName" >
          <template v-slot="{row}">
            <div class="flex-allcenter w100">
              <span class="more-width-20">{{row.belongBusinessName}}</span>
              <el-button type="text" icon="el-icon-copy-document" @click.stop="copyContent(row.belongBusinessName)"></el-button>
            </div>
          </template>
        </el-table-column>
        <el-table-column label="小程序" align="center" prop="" width="110">
          <template v-slot="{row}">
            <el-button type="text" @click="openSelectLanguage(row, 1)">配置</el-button>
          </template>
        </el-table-column>
        <el-table-column label="采收批次说明" align="center" prop="remarks" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template v-slot="{row}">
            <el-button size="mini" type="text" @click="openSelectLanguage(row, 2)"
                       v-hasPermi="['product:harvest-batch:query']">预览</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <pagination v-show="total > 0" :total="total" :page.sync="searchFormParam.queryParams.pageNo" :limit.sync="searchFormParam.queryParams.pageSize"
                  @pagination="getList"/>
    </div>
    <!-- 选择语言 -->
    <el-dialog
      title="选择语言"
      :visible.sync="selectLanguage"
      width="400px"
      :before-close="closeSelectLanguage"
      append-to-body
    >
      <el-form :model="languageForm" 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="goToSetting">确定</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 {
  deleteHarvestBatch,
  getHarvestBatchPage,
  exportHarvestBatchExcel,
  previewLinkConfig,
  getHarverstActive,
  getHarverstFreeze,
  initConfig,
} from "@/api/production/harvestBatch";
import { getAllLanguageType } from "@/api/system/languageType";
import SearchForm from '@/components/Customer/SearchForm'
import appPreview from '@/components/Customer/appPreview'
export default {
  name: "HarvestBatch",
  components: {
    SearchForm,
    appPreview
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 采收批次列表
      list: [],
      // 弹出层标题
      title: "",
      searchFormParam: {
        // 查询参数
        queryParams: {
          pageNo: 1,
          pageSize: 10,
          harvestBatchId: null,
          harvestId: null,
          harvestDate: [],
          goodsName: null,
          goodsId: null,
          goodsNum: null,
          blockChainId: null,
          blockChainBlockIdentity: null,
          blockState: null,
          templateName: null,
          templateId: null,
          remarks: null,
          createTime: [],
          belongBusinessId: null,
          belongBusinessName: null,
        },
        dataSource:[
          {
            key:'harvestBatchId',
            itemType:'input',
            label:'采收批次编号',
            placeholder:'请输入采收批次编号',
            onEnterKeyUp:this.handleQuery
          },
          {
            key:'harvestId',
            itemType:'input',
            label:'采收入库编号',
            placeholder:'请输入采收入库编号',
            onEnterKeyUp:this.handleQuery
          },
          {
            key:'harvestDate',
            itemType:'datePicker',
            label:'采收批次日期',
            placeholder:'请选择采收批次日期',
            onEnterKeyUp:this.handleQuery
          },
          {
            key:'goodsName',
            itemType:'input',
            label:'商品名称',
            placeholder:'请输入商品名称',
            onEnterKeyUp:this.handleQuery
          },
          {
            key:'belongBusinessName',
            itemType:'input',
            label:'所属商户',
            placeholder:'请输入所属商户',
            onEnterKeyUp:this.handleQuery
          },
        ],
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        harvestBatchId: [{ required: true, message: "采收批次id不能为空", trigger: "blur" }],
        harvestId: [{ required: true, message: "入库单号不能为空", trigger: "blur" }],
        harvestDate: [{ required: true, message: "入库日期不能为空", trigger: "blur" }],
        goodsName: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
        goodsId: [{ required: true, message: "商品id不能为空", trigger: "blur" }],
        blockState: [{ required: true, message: "批次上传状态不能为空", trigger: "blur" }],// 0：未上传  1：激活状态  2：冻结状态
        belongBusinessId: [{ required: true, message: "所属商户id不能为空", trigger: "blur" }],
        belongBusinessName: [{ required: true, message: "所属商户名称不能为空", trigger: "blur" }],
      },
      previewInfo: {},
      dialogPreview: false,
      // 选择语言弹窗
      selectLanguage: false,
      languageList: [],
      languageForm: {},
      selectLanguageType: 1,
      selectHarvestBatchCode: null,
      selectHarvestBatchId: null,
    };
  },
  created() {
    this.getList();
  },
  methods: {
    openSelectLanguage(row, type) {
      this.resetForm("languageFormRef");
      this.selectLanguage = true;
      this.selectLanguageType = type;
      this.selectHarvestBatchCode = row.harvestBatchId;
      this.selectHarvestBatchId = row.id;
      getAllLanguageType().then(({ data }) => {
        this.languageList = data;
        if (data.length > 0) {
          this.languageForm.languageTypeId = data[0].id;
        }
      });
    },
    closeSelectLanguage() {
      this.selectLanguage = false;
    },
    goToSetting() {
      this.$refs["languageFormRef"].validate(valid => {
        if (!valid) {
          return;
        }
        this.selectLanguage = false;
        if (this.selectLanguageType === 1) {
          this.$router.push({
            path: '/production/setting/miniProConfig',
            query:{
              id: this.selectHarvestBatchId,
              typeId: this.languageForm.languageTypeId,
            }
          });
        } else {
          this.handlePreview(this.selectHarvestBatchCode, this.languageForm.languageTypeId);
        }
      })
    },
    filterText(blockState) {
      switch(blockState){
        case 0:
          return '未上传'
         case 1:
          return '已上传'
         case 2:
          return '冻结'
       default :
        break;
      }
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getHarvestBatchPage(this.searchFormParam.queryParams).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        harvestBatchId: undefined,
        harvestId: undefined,
        harvestDate: undefined,
        goodsName: undefined,
        goodsId: undefined,
        goodsNum: undefined,
        blockChainId: undefined,
        blockChainBlockIdentity: undefined,
        blockState: undefined,
        templateName: undefined,
        templateId: undefined,
        remarks: undefined,
        belongBusinessId: undefined,
        belongBusinessName: undefined,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.searchFormParam.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm", "searchForm");
      this.handleQuery();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除采收批次编号为"' + id + '"的数据项?').then(function() {
          return deleteHarvestBatch(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      // 处理查询参数
      let params = {...this.searchFormParam.queryParams};
      params.pageNo = undefined;
      params.pageSize = undefined;
      this.$modal.confirm('是否确认导出所有采收批次数据项?').then(() => {
          this.exportLoading = true;
          return exportHarvestBatchExcel(params);
        }).then(response => {
          this.$download.excel(response, '采收批次.xls');
          this.exportLoading = false;
        }).catch(() => {});
    },
    initializeConfig() {
      initConfig().then(() => {
        this.$message.success("初始化成功");
      }).catch(() => {});
    },
    // 预览小程序效果
    async handlePreview(harvestBatchId, languageTypeId){
      // 获取采收信息
      let { data } = await previewLinkConfig({ harvestBatchId, 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;
      });
    },

    handleState(row,type){
      const id = row.id;
      let text;
      switch(type){
        case 'upChain':
          text = '上传';
          break;
        case 'freeze':
          text = '冻结';
          break;
        case 'active':
          text = '激活';
          break;
      }
      this.$modal.confirm(`是否确认${text}采收入库编号为${id}的数据项?`).then(function() {
          switch(type){
            case 'upChain':
              return getHarverstUpChain(id);
            case 'freeze':
              return getHarverstFreeze(id);
            case 'active':
              return getHarverstActive(id);
          }
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess(`${text}成功`);
        }).catch(() => {});
    },
  }
};
</script>
<style scoped lang="scss">
  .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>
