<template>
  <div class="app-container">
    <div class="app-container-search main-bgcolor main-radius">
      <h1 class="">模板列表</h1>
      <br />
      <!-- 搜索工作栏 -->
      <SearchInfo
        ref="searchForm"
        :searchFormParam="{ queryParams , dataSource }"
        :showSearch.sync="showSearch"
        @handleQuery="handleQuery"
        @resetQuery="resetQuery"
      ></SearchInfo>
    </div>

    <div class="app-container-list main-bgcolor main-radius shopping">
      <div class="shopping-top">
        <div class="shopping-title">模板列表</div>
        <el-button class="shopping-add-btn" type="primary" plain @click="handleAdd"
                  v-hasPermi="['basic:goods-info:create']">新增模板</el-button>
      </div>

      <!-- 列表 -->
      <el-table v-loading="loading" :data="list">
        <el-table-column label="编号" align="center" type="index" width="80" >
          <template v-slot="{ $index }">
            <span>{{($index+1)+ (queryParams.pageNo-1)*queryParams.pageSize }}</span>
          </template>
        </el-table-column>
        <el-table-column label="模板名称" align="center" prop="templateName" />
        <el-table-column label="创建时间" align="center" prop="createTime" >
          <template v-slot="{ row }">
            <span>{{parseTime(row.createTime)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="所属商户" align="center" prop="belongBusinessName" />
        <el-table-column label="商品名称" align="center" prop="goodsName" />
        <el-table-column label="创建人" align="center" prop="creatorName" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template v-slot="scope">
            <el-button size="mini" type="text" @click="handleEdit(scope.row)"
                       v-hasPermi="['configure:trace-template:update']">详情</el-button>
            <el-button size="mini" type="text" @click="toSetting(scope.row,'/configue/trace-link')"
                       v-hasPermi="['configure:trace-template:update']">修改</el-button>
            <el-button size="mini" type="text" @click="handleDelete(scope.row)"
                       v-hasPermi="['configure:trace-template:delete']">删除</el-button>
          </template>
        </el-table-column>
      </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="模板名称" prop="templateName">
          <el-input v-model="form.templateName" placeholder="请输入模板名称" />
        </el-form-item>
        <el-form-item label="所属商户" prop="belongBusinessId">
          <el-select
          v-model="form.belongBusinessId"
          class="w100"
          ref="businessName"
          @change="handchangeBusiness"
          placeholder="请选择商户">
            <el-option v-for="item in businessNameList" :key="item.id" :label="item.businessName" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" prop="goodsId">
          <el-select
          v-model="form.goodsId"
          class="w100"
          ref="goodsName"
          @change="handchangeGoods"
          placeholder="请选择商品">
            <el-option v-for="item in goodsNameList" :key="item.goodsId" :label="item.goodsName" :value="item.goodsId" />
          </el-select>
        </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-drawer
      title="溯源信息详情"
      :visible.sync="drawerTemplate"
      direction="rtl">
      <div v-if="templateInfo.length == 0">
        <EmptyBound />
      </div>
      <div v-else>
        <operateShow :list="templateInfo" />
      </div>
    </el-drawer>
  </div>
</template>

<script>
import {
  createTraceTemplate,
  updateTraceTemplate,
  deleteTraceTemplate,
  getTraceTemplate,
  getTraceTemplatePage,
  exportTraceTemplateExcel,
  getTemplateDetail,
} from "@/api/configure/traceTemplate";
import { getBusinessNameList } from '@/api/basic/businessInfo';
import { getGoodsNameList } from '@/api/basic/goodsInfo';
import SearchInfo from '@/components/Customer/SearchForm'
import operateShow from '@/components/Customer/operateShow'
import EmptyBound from '@/components/EmptyTable'
export default {
  name: "TraceTemplate",
  components: {
    SearchInfo,
    operateShow,
    EmptyBound
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 溯源模板列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        templateId: null,
        templateName: null,
        goodsId: null,
        goodsName: null,
        belongBusinessId: null,
        belongBusinessName: null,
        createTime: [],
      },
      dataSource:[
        {
          key:'templateName',
          itemType:'input',
          label:'模板名称',
          placeholder:'请输入',
          onEnterKeyUp:this.handleQuery
        },
        {
          key:'belongBusinessName',
          itemType:'input',
          label:'所属商户',
          placeholder:'请输入',
          onEnterKeyUp:this.handleQuery
        },
        {
          key:'goodsName',
          itemType:'input',
          label:'商品名称',
          placeholder:'请输入',
          onEnterKeyUp:this.handleQuery
        },
      ],

      // 表单参数
      form: {},
      // 表单校验
      rules: {
        templateName: [{ required: true, message: "模板名称不能为空", trigger: "change" }],
        belongBusinessId: [{ required: true, message: "所属商户id不能为空", trigger: "change" }],
        belongBusinessName: [{ required: true, message: "所属商户名称不能为空", trigger: "change" }],
        goodsId: [{ required: true, message: "商品id不能为空", trigger: "change" }],
        goodsName: [{ required: true, message: "商品名称不能为空", trigger: "change" }],
      },
      // 所属商户列表
      businessNameList: [],
      // 商品列表
      goodsNameList: [],
      // 抽屉-详情是否打开
      drawerTemplate: false,
      // 溯源模板详情参数
      templateInfo: [],
    };
  },
  created() {
    this.getList();
    this.initDate();
  },
  methods: {
    toSetting(row,path){
      this.$router.push({
        path,
        query:{
          templateId: row.templateId,
          id: row.id,
        }
      })
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getTraceTemplatePage(this.queryParams).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    // 初始化参数
    async initDate(){
      let res = await getBusinessNameList();
      this.businessNameList = res.data;
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        templateId: undefined,
        templateName: undefined,
        goodsId: undefined,
        goodsName: undefined,
        belongBusinessId: undefined,
        belongBusinessName: 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 = "添加溯源模板";
    },
    /** 详情按钮操作 */
    async handleEdit(row){
      const templateId = row.templateId;
      let res = await getTemplateDetail({templateId});
      this.drawerTemplate = true;
      this.templateInfo = res.data;
      console.log('详情',res);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getTraceTemplate(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) {
          updateTraceTemplate(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createTraceTemplate(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 deleteTraceTemplate(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 exportTraceTemplateExcel(params);
        }).then(response => {
          this.$download.excel(response, '溯源模板.xls');
          this.exportLoading = false;
        }).catch(() => {});
    },
    // 所属商户修改
    async handchangeBusiness(ids){
      this.$nextTick(()=>{
         this.form.belongBusinessName = this.$refs.businessName.selected.label;
      });
      this.form.goodsId = '';
      this.form.goodsName = '';
      let res = await getGoodsNameList({ids});
      this.goodsNameList = res.data;
    },
    handchangeGoods(e){
      this.$nextTick(()=>{
         this.form.goodsName = this.$refs.goodsName.selected.label;
      });
    },
  }
};
</script>
