<template>
  <div class="app-container">
    <div class="app-container-search main-bgcolor main-radius">
      <h1 class="">商品认证</h1>
      <br />
      <!-- 搜索工作栏 -->
      <SearchForm
        ref="searchForm"
        :searchFormParam="{ queryParams , dataSource }"
        :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>
        <el-button class="shopping-add-btn" type="primary" plain @click="handleAdd" style="height: 32px;"
          v-hasPermi="['basic:goods-verify: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="goodsName">
          <template v-slot="{ row }">
            <span v-if="row.goodsId != undefined && row.goodsId != null">{{row.goodsName}}</span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column label="认证名称" align="center" prop="verifyName" />
        <el-table-column label="认证机构" align="center" prop="verifyAgencies" />
        <el-table-column label="有效期" align="center" prop="verifyStartTime" >
          <template v-slot="{ row }">
            <span v-if="!row.verifyIsForver">{{parseTime(row.verifyStartTime,'{y}-{m}-{d}')}}~{{parseTime(row.verifyEndTime,'{y}-{m}-{d}')}}</span>
            <span v-if="row.verifyIsForver">{{parseTime(row.verifyStartTime,'{y}-{m}-{d}')}}~长期</span>
          </template>
        </el-table-column>
        <el-table-column label="所属商户" align="center" prop="belongBusinessName" />
        <el-table-column label="操作" fixed="right" class-name="small-padding fixed-width" width="150" >
          <template v-slot="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                      v-hasPermi="['basic:goods-verify:update']">编辑</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                      v-hasPermi="['basic:goods-verify:delete']">删除</el-button>
          </template>
        </el-table-column>
        <div slot="empty">
            <EmptyTable />
        </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" class="goods-verify" :visible.sync="open" width="530px"  append-to-body>
      <el-form ref="form" label-position="top" :rules="rules" :model="form" label-width="80px">
        <el-form-item label="所属商户" prop="belongBusinessId">
          <el-select ref="businessName" :disabled="openStats=='edit'" @change="handchangeBusiness" v-model="form.belongBusinessId" 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 ref="goodsName" @change="handChangeGoods" v-model="form.goodsId" placeholder="请选择商品名称">
            <el-option v-for="item in goodsNameList" :key="item.id" :label="item.goodsName" :value="item.goodsId" />
          </el-select>
        </el-form-item>
        <el-form-item label="认证名称" prop="verifyName">
          <el-input v-model="form.verifyName" placeholder="请输入认证名称" />
        </el-form-item>
        <el-form-item label="有效期" prop="verifyStartTime">
          <div>
            <el-radio-group v-model="form.verifyIsForver" @change="form.verifyStartTime = undefined , verifyTimeLong = undefined , verifyTimeSort = undefined">
              <el-radio :label="false">时间段</el-radio>
              <el-radio :label="true">长期</el-radio>
            </el-radio-group>
          </div>
          <el-date-picker
              v-if="!form.verifyIsForver"
              v-model="verifyTimeSort"
              @change="handChangeForverSort"
              value-format="yyyy-MM-dd HH:mm:ss" type="daterange"
              range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期"
              :default-time="['00:00:00', '23:59:59']"
              :style="{width: '100%'}"
          />
          <div v-if="form.verifyIsForver" >
            <el-date-picker clearable @change="handChangeForverLong" v-model="verifyTimeLong" type="date" value-format="timestamp" placeholder="选择有效起始时间" />
            <span>~长期</span>
          </div>
        </el-form-item>
        <el-form-item label="认证机构" prop="verifyAgencies">
          <el-input v-model="form.verifyAgencies" placeholder="请输入认证机构" />
        </el-form-item>
        <el-form-item label="认证资料(最多上传6张)" prop="verifyAgencies">
          <file-upload class="verifyFileUpload" v-model="form.verifyDataUrl" :limit="6" :fileType="['jpg','jpeg','png','pdf']" :fileSize="20"></file-upload>
        </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>

  </div>
</template>

<script>
import { createGoodsVerify, updateGoodsVerify, deleteGoodsVerify, getGoodsVerify, getGoodsVerifyPage } from "@/api/basic/goodsVerify";
import SearchForm from '@/components/Customer/SearchForm';
import FileUpload from "@/components/FileUpload";
import EmptyTable from '@/components/EmptyTable'
import { getBusinessNameList } from '@/api/basic/businessInfo';
import { getGoodsNameList } from '@/api/basic/goodsInfo'
export default {
  name: "GoodsVerify",
  components: {
    SearchForm,
    EmptyTable,
    FileUpload
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      //头部查询表单组件的参数
      dataSource:[
        {
          key:'goodsName',
          itemType:'input',
          label:'商品名称',
          placeholder:'请输入商品名称',
          onEnterKeyUp:this.handleQuery,
        },
        {
          key:'verifyName',
          itemType:'input',
          label:'认证名称',
          placeholder:'请输入认证名称',
          onEnterKeyUp:this.handleQuery
        },
        {
          key:'verifyAgencies',
          itemType:'input',
          label:'认证机构',
          placeholder:'请输入认证机构',
          onEnterKeyUp:this.handleQuery
        },
        {
          key:'verifyStartTime',
          itemType:'datePicker',
          label:'有效期',
          placeholder:'请选择',
          onEnterKeyUp:this.handleQuery
        },
        {
          key:'belongBusinessName',
          itemType:'input',
          label:'所属商户',
          placeholder:'请输入所属商户',
          onEnterKeyUp:this.handleQuery
        },
      ],
      // 总条数
      total: 0,
      // 商品认证列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 弹窗为修改edit时，所属商户禁用
      openStats: 'add',
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        goodsName: null,
        goodsId: null,
        verifyName: null,
        verifyAgencies: null,
        verifyStartTime: [],
        verifyEndTime: [],
        verifyDataUrl: null,
        verifyIsForver: null,
        createTime: [],
        belongBusinessId: null,
        belongBusinessName: null,
      },
      // 表单参数
      form: {},
      // 有效期-长期 临时
      verifyTimeLong: '',
      // 有效期-时间段 临时
      verifyTimeSort: '',
      // 表单校验
      rules: {
        goodsName: [{ required: true, message: "商品名称不能为空", trigger: "blur" }],
        goodsId: [{ required: true, message: "选择商品不能为空", trigger: "blur" }],
        verifyName: [{ required: true, message: "认证名称不能为空", trigger: "blur" }],
        verifyAgencies: [{ required: true, message: "认证机构不能为空", trigger: "blur" }],
        verifyStartTime: [{ required: true, message: "有效起始时间不能为空", trigger: "blur" }],
        verifyDataUrl: [{ required: true, message: "认证资料不能为空", trigger: "blur" }],
        verifyIsForver: [{ required: true, message: "是否长期有效不能为空", trigger: "blur" }],
        belongBusinessId: [{ required: true, message: "所属商户id不能为空", trigger: "blur" }],
        belongBusinessName: [{ required: true, message: "所属商户名称不能为空", trigger: "blur" }],
      },
      // 商户名称列表
      businessNameList: [],
      // 商品名称列表
      goodsNameList: [],
    };
  },
  created() {
    this.getList();
    this.getBusinessNameList();
  },
  methods: {
    /** 查询列表 */
    getList() {
      this.loading = true;
      if(this.queryParams.verifyAgencies == ''){
        this.queryParams.verifyAgencies = null;
      }
      // 执行查询
      getGoodsVerifyPage(this.queryParams).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.form = {
        id: undefined,
        goodsName: undefined,
        goodsId: undefined,
        verifyName: undefined,
        verifyAgencies: undefined,
        verifyStartTime: undefined,
        verifyEndTime: undefined,
        verifyDataUrl: undefined,
        verifyIsForver: false,
        belongBusinessId: undefined,
        belongBusinessName: undefined,
      };
      this.verifyTimeLong = '';
      this.verifyTimeSort = '';
      this.resetForm("form");
    },
    selectChage({ value, type, book }) {
      if (type != 'goodsName') {
        this.queryParams.goodsName = ''
      }
      if (!book) {
        return
      }
      getGoodsNameList({
        ids: value,
      }).then((res) => {
        console.log(res, 'res')
        this.$nextTick(() => {
          this.dataSource[1].options = res.data.map((el) => {
            let obj = {
              label: el.goodsName,
              value: el.id,
              key: el.id,
            }
            return obj
          })
        })
      })
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm", "searchForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品认证";
      this.openStats = 'add';
    },
    /** 修改按钮操作 */
    async handleUpdate(row) {
      this.verifyTimeLong = '';
      this.verifyTimeSort = '';
      this.reset();
      const id = row.id;
      let rest = await getGoodsNameList({ids: row.belongBusinessId});
      this.goodsNameList = rest.data;
      getGoodsVerify(id).then(async response => {
        let data = response.data;
        if( data.verifyStartTime  ) data.verifyStartTime = await this.parseTime(data.verifyStartTime);
        if( data.verifyEndTime  ) data.verifyEndTime = await this.parseTime(data.verifyEndTime);
        if( data.verifyIsForver ){
          this.verifyTimeLong = Date.parse( data.verifyStartTime );
        }else{
          this.verifyTimeSort = [data.verifyStartTime , data.verifyEndTime];
        }
        // data.goodsId = parseInt(data.goodsId);
        //当商品被删除时，无法显示对应的商品名称，重新定义
        let isTip = false;
        for(var x=0;x<this.goodsNameList.length;x++){
          if(this.goodsNameList[x].goodsId === data.goodsId){
            isTip = true;
          }
        }
        if( !isTip ) data.goodsId = '商品已删除，请重新选择'
        this.form = data;
        this.open = true;
        this.title = "修改商品认证";
        this.handchangeBusiness(row.belongBusinessId,false);
        this.openStats = 'edit';
      });
    },
    /** 提交按钮 */
    submitForm() {
      console.log(this.form.verifyIsForver , this.form.verifyStartTime , this.form.verifyEndTime);
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        if( this.form.verifyIsForver && !this.form.verifyStartTime ){
          this.$message.error("有效期为长期时，开始时间不能为空");
          return;
        }
        if( !this.form.verifyIsForver && (!this.form.verifyStartTime || !this.form.verifyEndTime) ){
          this.$message.error("有效期为时间段时，开始和结束时间不能为空");
          return;
        }
        // 修改的提交
        if (this.form.id != null) {
          updateGoodsVerify(this.form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createGoodsVerify(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 deleteGoodsVerify(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    // 获取商户列表
    getBusinessNameList(){
      getBusinessNameList().then(res => {
        this.businessNameList = res.data;
      });
    },
    // 绑定所属商户id的同时绑定所属商户名称
    handchangeBusiness(e,isNeed = true){
      this.$nextTick(()=>{
         this.form.belongBusinessName = this.$refs.businessName.selected.label;
         if(isNeed){
           getGoodsNameList({
             ids: e,
           }).then((res) => {
             this.$nextTick(() => {
               this.goodsNameList = res.data;
             })
           })
         }
      });
    },
    handChangeGoods(){
      this.$nextTick(()=>{
        console.log(this.$refs.goodsName.selected);
        this.form.goodsName = this.$refs.goodsName.selected.label;
      });
    },
    // 选择有效期-时间段
    handChangeForverSort(e){
      this.form.verifyStartTime = Date.parse(e[0]);
      this.form.verifyEndTime = Date.parse(e[1]);
    },
    // 选择有效期-长期
    handChangeForverLong(e){
      this.form.verifyStartTime = e;
    },
  }
};
</script>
<style scoped lang="scss">
  .goods-verify{
    .el-select{
      width: 100%;
    }
    .el-date-editor{
      width: 90%;
    }
  }

  .hide {
    ::v-deep .el-upload--picture-card {
      display: none !important;
    }
  }

  .verifyFileUpload{
    ::v-deep .upload-file-list{
      .el-upload-list__item{
        width: 100%;
        .el-link{
          width: calc(100% - 70px);
          .el-link--inner{
            width: 100%;
            display: flex;
            align-items: center;
          }
        }
        .el-link--danger{
          white-space: nowrap;
        }
      }
      .el-icon-document{
        white-space:nowrap;
        text-overflow: ellipsis;
        overflow: hidden;
        max-width: calc(100% - 14px - 20px);
      }
    }
  }
</style>
