<template>
  <div class="app-container-gray padding-6">
    <el-card class="card-margin-bottom">
      <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px" class="form-minus-bottom">
        <base-select v-model="queryParams.baseId"></base-select>
        <el-form-item label="产品名称" prop="sellproName">
          <el-input v-model="queryParams.sellproName" placeholder="请输入产品名称" clearable size="small" @keyup.enter.native="handleQuery" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
        <el-form-item class="fr">
          <el-button v-if="!isAdmin" type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd" v-hasPermi="['trace:sellpro:add']"
            >新增</el-button
          >
          <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['trace:sellpro:export']"
            >导出</el-button
          >
          <el-button type="primary" icon="el-icon-sort" size="mini" plain @click="viewMode = !viewMode">视图</el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card class="card-padding-bottom" v-if="viewMode">
      <el-table v-loading="loading" :data="sellproList">
        <el-table-column label="产品名称" align="center" prop="sellproName" />
        <el-table-column label="产品图片" align="center" prop="sellproImg" width="180">
          <template v-slot:default="{ row }">
            <div class="image" @click="previewImage(`${row.sellproImg}`, row)">
              <img style="width: 50px; height: 50px" :src="`${row.sellproImg}`" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="产地" align="center" prop="sellproArea" />
        <el-table-column label="产品重量" align="center" prop="sellproWeight" />
        <el-table-column label="产品规格" align="center" prop="sellproGuige" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="small"
              type="primary"
              class="padding-5"
              icon="el-icon-c-scale-to-original"
              @click="handleGenerateCode(scope.row)"
              v-hasPermi="['trace:sellpro:generateCode']"
              >生成溯源码</el-button
            >
            <el-button
              size="small"
              type="warning"
              class="padding-5"
              icon="el-icon-edit"
              @click="handleUpdate(scope.row)"
              v-hasPermi="['trace:sellpro:edit']"
              >修改</el-button
            >
            <el-button
              size="small"
              type="danger"
              class="padding-5"
              icon="el-icon-delete"
              @click="handleDelete(scope.row)"
              v-hasPermi="['trace:sellpro:remove']"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />
    </el-card>
    <div v-if="!viewMode">
      <el-row :gutter="15">
        <el-col :span="6" v-for="item in sellproList" :key="item.sellproId">
          <div class="w100 background-color-fff padding-15 border-radius-10 margin-bottom-10">
            <div class="flex jcsb">
              <div class="flex fdc">
                <span class="font-size-20 font-color-main">{{ item.sellproName }}</span>
                <span class="font-size-13 font-color-secondary">{{ item.remark }}</span>
              </div>
              <img :src="image.baseUrl + item.sellproImg" class="width-80 height-80 border-radius-10" alt="" />
            </div>
            <div class="flex jcsb padding-tb-12 border-bottom-eee">
              <span class="font-size-13 font-color-main">产地</span>
              <span class="font-size-13 font-color-main">{{ item.sellproArea }}</span>
            </div>
            <div class="flex jcsb padding-tb-12 border-bottom-eee">
              <span class="font-size-13 font-color-main">产品重量</span>
              <span class="font-size-13 font-color-main">{{ item.sellproWeight }}</span>
            </div>
            <div class="flex jcsb padding-tb-12 border-bottom-eee">
              <span class="font-size-13 font-color-main">产品规格</span>
              <span class="font-size-13 font-color-main">{{ item.sellproGuige }}</span>
            </div>
            <div class="flex jcc aic margin-top-20">
              <el-button-group size="mini" class="margin-center">
                <el-button
                  type="primary"
                  size="mini"
                  style="padding: 5px 10px"
                  icon="el-icon-c-scale-to-original"
                  @click="handleGenerateCode(item)"
                  v-hasPermi="['trace:sellpro:generateCode']"
                  >生成溯源码</el-button
                >
                <el-button
                  type="warning"
                  size="mini"
                  style="padding: 5px 10px"
                  icon="el-icon-edit"
                  @click="handleUpdate(item)"
                  v-hasPermi="['trace:sellpro:edit']"
                  >修改</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  style="padding: 5px 10px"
                  icon="el-icon-delete"
                  @click="handleDelete(item)"
                  v-hasPermi="['trace:sellpro:remove']"
                  >删除</el-button
                >
              </el-button-group>
            </div>
          </div>
        </el-col>
      </el-row>
      <pagination
        class="background-none"
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
      <div v-if="total == 0" class="flex aic jcc w100 hbm30">
        <el-empty description="暂无溯源产品"> </el-empty>
      </div>
    </div>
    <!-- 添加或修改溯源产品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-row :gutter="20">
          <el-col :span="12" :offset="0">
            <el-form-item label="产品名称" prop="sellproName">
              <el-input v-model="form.sellproName" placeholder="请输入产品名称" />
            </el-form-item>
            <el-form-item label="产品产地" prop="sellproArea">
              <el-input v-model="form.sellproArea" placeholder="请输入产地" />
            </el-form-item>
            <el-form-item label="溯源码模版" prop="codeTemplateId">
              <el-select v-model="form.codeTemplateId" placeholder="请选择溯源码模版" clearable filterable>
                <el-option v-for="item in codeTemplateList" :key="item.templateId" :label="item.templateName" :value="item.templateId"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品重量" prop="sellproWeight">
              <el-input v-model="form.sellproWeight" placeholder="请输入产品重量" />
            </el-form-item>
            <el-form-item label="产品规格" prop="sellproGuige">
              <el-input v-model="form.sellproGuige" placeholder="请输入产品规格" />
            </el-form-item>
            <el-form-item label="溯源页面模版" prop="templateId">
              <el-select v-model="form.templateId" placeholder="请选择溯源页面模版" clearable filterable>
                <el-option v-for="item in templateList" :key="item.templateId" :label="item.templateName" :value="item.templateId"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="产品介绍" prop="remark" size="normal">
              <el-input v-model="form.remark" placeholder="请输入产品介绍" size="normal" type="textarea"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="24" :offset="0">
            <el-form-item label="产品图片" prop="sellproImg">
              <imageUpload v-model="form.sellproImg" :limit="1" />
            </el-form-item>
          </el-col>
        </el-row>
      </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="openGenrateCode" width="420px" @close="openGenrateCode = false">
      <el-form :model="genrateForm" ref="genrateForm" :rules="generateRules" label-width="110px" :inline="false" size="normal">
        <el-alert
          class="margin-bottom-20"
          title="生成数量过多时需要耐性等待，1000条大约3-6秒"
          type="warning"
          effect="light"
          show-icon
          closable
        ></el-alert>

        <el-form-item prop="perfix">
          <template #label>
            编号前缀
            <el-tooltip content="例如：填写编号前缀XY，那么生成的溯源码格式为XY2024030312053400001" placement="top" effect="dark">
              <i class="el-icon-info"></i>
            </el-tooltip>
          </template>
          <el-input v-model="genrateForm.perfix" placeholder="编号前缀" :disabled="loadingVisiable">
            <template #append>{{ getCurrentDateTime() }}00001</template>
          </el-input>
        </el-form-item>
        <el-form-item prop="number">
          <template #label>
            生成数量
            <el-tooltip content="每次最多生成1000个" placement="top" effect="dark">
              <i class="el-icon-info"></i>
            </el-tooltip>
          </template>
          <el-input-number class="w100" v-model="genrateForm.number" :min="1" :max="1000" :disabled="loadingVisiable"></el-input-number>
        </el-form-item>
      </el-form>

      <span slot="footer">
        <el-button type="primary" @click="conformGenerateCode" :disabled="loadingVisiable" :icon="loadingVisiable ? 'el-icon-loading' : ''"
          >确定</el-button
        >
        <el-button @click="openGenrateCode = false" :disabled="loadingVisiable">取消</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { listSellpro, getSellpro, delSellpro, addSellpro, updateSellpro, generateCode } from '@/api/trace/sellpro';
import { listTraceCodeTemplate } from '@/api/trace/traceCodeTemplate';
import { listTraceTemplate } from '@/api/trace/traceTemplate';
import { mapGetters } from 'vuex';

export default {
  name: 'Sellpro',
  dicts: ['sys_user_sex', 'sys_user_sex', 'sys_user_sex', 'sys_user_sex', 'sys_user_sex', 'sys_user_sex', 'sys_user_sex'],
  data() {
    return {
      //图片预览
      image: {
        baseUrl: window.location.origin + process.env.VUE_APP_BASE_API,
        open: false,
        imgUrl: '',
        title: '',
      },
      //视图模式
      viewMode: false,
      codeTemplateList: [],
      templateList: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 溯源产品表格数据
      sellproList: [],
      // 弹出层标题
      title: '',
      // 是否显示产品弹出层
      open: false,
      //是否显示生成溯源码弹出层
      openGenrateCode: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        sellproName: null,
        germplasmId: null,
        baseId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        sellproName: [{ required: true, message: '产品名称不能为空', trigger: 'blur' }],
        sellproImg: [{ required: true, message: '产品图片不能为空', trigger: 'blur' }],
        remark: [{ required: true, message: '产品介绍不能为空', trigger: 'blur' }],
        sellproArea: [{ required: true, message: '产地不能为空', trigger: 'blur' }],
        sellproWeight: [{ required: true, message: '产品重量不能为空', trigger: 'blur' }],
        sellproGuige: [{ required: true, message: '产品规格不能为空', trigger: 'blur' }],
        templateId: [{ required: true, message: '溯源模版不能为空', trigger: 'blur' }],
        codeTemplateId: [{ required: true, message: '溯源码模版不能为空', trigger: 'blur' }],
      },
      //当前需要生成溯源码的产品数据
      currentSellPro: null,
      genrateForm: {
        perfix: 'frog',
        number: 10,
      },
      generateRules: {
        perfix: [{ required: true, message: '产品编号前缀不能为空', trigger: 'blur' }],
        number: [{ required: true, message: '生成数量不能为空', trigger: 'blur' }],
      },
      //进度条参数
      loadingVisiable: false,
      progressPercentage: 0,
    };
  },
  computed: {
    ...mapGetters(['isAdmin']),
  },

  async created() {
    this.getList();
    this.getCodeTemplateList();
    this.getTemplateList();
  },
  methods: {
    /** 查询溯源产品列表 */
    getList() {
      this.loading = true;
      listSellpro(this.queryParams).then((response) => {
        this.sellproList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询溯源码模版列表 */
    async getCodeTemplateList() {
      const { rows } = await listTraceCodeTemplate({ status: 0 });
      this.codeTemplateList = rows;
    },
    /** 查询溯源页面模版列表 */
    async getTemplateList() {
      const { rows } = await listTraceTemplate({ status: 0 });
      this.templateList = rows;
    },

    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        sellproId: null,
        sellproName: null,
        sellproArea: null,
        sellproWeight: null,
        sellproGuige: null,
        remark: null,
        status: '1',
        orderNum: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        delFlag: null,
        sellproImg: null,
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = '添加溯源产品';
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const sellproId = row.sellproId || this.ids;
      getSellpro(sellproId).then((response) => {
        this.form = response.data;
        this.open = true;
        this.title = '修改溯源产品';
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.sellproId != null) {
            updateSellpro(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addSellpro(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const sellproIds = row.sellproId || this.ids;
      this.$modal
        .confirm('是否确认删除溯源产品编号为"' + sellproIds + '"的数据项？')
        .then(function () {
          return delSellpro(sellproIds);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => {});
    },
    /** 处理生成溯源码按钮点击 */
    handleGenerateCode(row) {
      this.openGenrateCode = true;
      this.currentSellPro = row;
    },
    /** 确认生成溯源码 */
    conformGenerateCode() {
      this.loadingVisiable = true;
      const { sellproId } = this.currentSellPro;
      const { perfix, number } = this.genrateForm;
      //拼接溯源码地址，http://xxx.xxx.xxx:xx/preview?traceCode=
      let url = window.location.protocol + '//' + window.location.host + '/preview?traceCode=';
      generateCode({ sellproId, perfix, number, url })
        .then((res) => {
          this.openGenrateCode = false;
          this.loadingVisiable = false;
          if (res.data == 1) {
            this.$modal.msgSuccess('生成成功');
          } else {
            this.$modal.msgSuccess('生成失败');
          }
        })
        .catch((error) => {
          this.openGenrateCode = false;
          this.loadingVisiable = false;
        });
    },
    /** 图片预览按钮操作 */
    previewImage(imgUrl, row) {
      this.image.title = row.version;
      this.image.open = true;
      this.image.imgUrl = imgUrl;
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'trace/sellpro/export',
        {
          ...this.queryParams,
        },
        `sellpro_${new Date().getTime()}.xlsx`
      );
    },
    /** 获取时间函数 */
    getCurrentDateTime() {
      const currentDate = new Date();
      const year = currentDate.getFullYear();
      const month = String(currentDate.getMonth() + 1).padStart(2, '0');
      const day = String(currentDate.getDate()).padStart(2, '0');
      const hours = String(currentDate.getHours()).padStart(2, '0');
      const minutes = String(currentDate.getMinutes()).padStart(2, '0');
      const seconds = String(currentDate.getSeconds()).padStart(2, '0');
      const formattedDateTime = `${year}${month}${day}${hours}${minutes}${seconds}`;
      return formattedDateTime;
    },
  },
};
</script>
