<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" >

      <el-form-item :label="$t('youhuijuanquanyi.优惠券')" prop="name">
        <el-input
          v-model="queryParams.name"
          :placeholder="$t('youhuijuanquanyi.请输入优惠券名称')"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">{{$t('youhuijuanquanyi.搜索')}}</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">{{$t('youhuijuanquanyi.重置')}}</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:quanyi:add']"
        >{{$t('youhuijuanquanyi.新增')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:quanyi:edit']"
        >{{$t('youhuijuanquanyi.修改')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:quanyi:remove']"
        >{{$t('youhuijuanquanyi.删除')}}</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['system:quanyi:export']"
        >{{$t('youhuijuanquanyi.导出')}}</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="quanyiList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="id" align="center" prop="id" width="50px"/>
<!--      <el-table-column :label="$t('youhuijuanquanyi.是否会员可用')" align="center" prop="vip">-->
<!--        <template slot-scope="scope">-->
<!--          <el-tag v-if="scope.row.vip==0" type="danger" effect="dark">{{generateTitle('是')}}</el-tag>-->
<!--          <el-tag v-if="scope.row.vip==1" type="info" effect="dark">{{generateTitle('否')}}</el-tag>-->
<!--        </template>-->
<!--      </el-table-column>-->
      <el-table-column :label="$t('youhuijuanquanyi.商家名称')" align="center" prop="merchantName" />
      <el-table-column :label="$t('youhuijuanquanyi.店铺名称')" align="center" prop="storeName" />
      <el-table-column :label="$t('youhuijuanquanyi.优惠券名称')" align="center" prop="name" />
      <el-table-column :label="$t('youhuijuanquanyi.优惠方式')" align="center" prop="yhfangs">
        <template slot-scope="scope">
<!--          <dict-tag :options="dict.type.sys_vip_youhui" :value="scope.row.yhfangs"/>-->
          <el-tag v-if="scope.row.yhfangs==1" >{{generateTitle('运费')}}</el-tag>
          <el-tag v-if="scope.row.yhfangs==2" >{{generateTitle('订单')}}</el-tag>
          <el-tag v-if="scope.row.yhfangs==3" >{{generateTitle('商品')}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('youhuijuanquanyi.优惠券状态')" align="center" prop="state">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.state==0" type="primary">{{generateTitle('启用')}}</el-tag>
          <el-tag v-if="scope.row.state==1" type="danger">{{generateTitle('停用')}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column :label="$t('youhuijuanquanyi.折扣金额')" align="center" prop="yhnum" />
      <el-table-column :label="$t('youhuijuanquanyi.有效期')" align="center" prop="validity" />
      <el-table-column :label="$t('youhuijuanquanyi.说明')" align="center" prop="shuoming" />
      <el-table-column :label="$t('youhuijuanquanyi.使用条件')" align="center" prop="tiaojian" />
      <el-table-column :label="$t('youhuijuanquanyi.已领取数量')" align="center" prop="claimedCount" />
      <el-table-column :label="$t('youhuijuanquanyi.操作')" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['system:quanyi:edit']"
          >{{$t('youhuijuanquanyi.修改')}}</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:quanyi:remove']"
          >{{$t('youhuijuanquanyi.删除')}}</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"
    />

    <!-- 添加或修改quanyi对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <!-- 红色提示框 -->
      <el-alert
        v-if="!form.edit"
        :title="$t('youhuijuanquanyi.不能修改提示')"
        type="error"
        show-icon
        :closable="false"
        style="margin-bottom: 16px;"
      />
      <el-form ref="form" :model="form" :rules="rules" :label-width="$t('message.language')=='语言'?'80px':$t('message.language')=='language'?'165px':'165px'">
        <el-form-item :label="$t('youhuijuanquanyi.商家名称')"  prop="merchantName">
          <el-input
            v-model="form.merchantName"
            :placeholder="$t('youhuijuanquanyi.请选择商家')"
            readonly
            style="width: 300px; margin-right: 10px;"
          />
          <el-button :disabled="!form.edit" type="primary" @click="showMerchantDialog = true">{{$t('youhuijuanquanyi.选择商家')}}</el-button>
        </el-form-item>
        <el-form-item :label="$t('youhuijuanquanyi.店铺名称')"  prop="shId">
          <el-select :disabled="!form.edit"  v-model="form.shId" :placeholder="$t('youhuijuanquanyi.请选择店铺')" style="width: 300px; margin-right: 10px;" clearable>
            <el-option
              v-for="dict in storeList"
              :key="dict.id"
              :label="dict.posName"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('youhuijuanquanyi.优惠方式')" prop="yhfangs">
          <el-radio-group v-model="form.yhfangs" :disabled="!form.edit">
            <el-radio
              v-for="dict in dict.type.sys_vip_youhui"
              :key="dict.value"
              :label="parseInt(dict.value)"
            >{{generateTitle(dict.label)}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('youhuijuanquanyi.优惠券名')" prop="name">
          <el-input v-model="form.name" :placeholder="$t('youhuijuanquanyi.请输入优惠券名称')" :readonly="!form.edit"/>
        </el-form-item>
        <el-form-item :label="$t('youhuijuanquanyi.优惠值')" prop="yhnum">
          <el-input type="number"  v-model="form.yhnum" :placeholder="$t('youhuijuanquanyi.请输入优惠值')" :readonly="!form.edit"/>
        </el-form-item>
        <el-form-item :label="$t('youhuijuanquanyi.优惠券总数')" prop="total">
          <el-input type="number" v-model="form.total" :placeholder="$t('youhuijuanquanyi.优惠券总数')" :readonly="!form.edit"/>
        </el-form-item>
        <el-form-item :label="$t('youhuijuanquanyi.每人能领取的数量')" prop="lqxz">
          <el-input type="number" v-model="form.lqxz" :placeholder="$t('youhuijuanquanyi.请输入每人能领取的数量')" :readonly="!form.edit"/>
        </el-form-item>
        <el-form-item :label="$t('youhuijuanquanyi.有效期')" prop="validity">
          <el-input v-model="form.validity"  type="number" min="1" :placeholder="$t('youhuijuanquanyi.请输入有效期')" :readonly="!form.edit"/>
        </el-form-item>
        <el-form-item :label="$t('youhuijuanquanyi.说明')" prop="shuoming">
          <el-input v-model="form.shuoming" :placeholder="$t('youhuijuanquanyi.请输入说明')" :readonly="!form.edit"/>
        </el-form-item>
        <el-form-item :label="$t('youhuijuanquanyi.使用条件')" prop="tiaojian">
          <el-input v-model="form.tiaojian" :placeholder="$t('youhuijuanquanyi.请输入使用条件')" :readonly="!form.edit"/>
        </el-form-item>
<!--        <el-form-item v-if="form.vip==0" :label="$t('youhuijuanquanyi.可用次数')" prop="num">-->
<!--          <el-input v-model="form.num" :placeholder="$t('youhuijuanquanyi.请输入每月会员可用次数')" />-->
<!--        </el-form-item>-->
        <el-form-item :label="$t('youhuijuanquanyi.优惠券状态')" prop="state">
          <el-radio-group v-model="form.state">
            <el-radio
              v-for="dict in dict.type.sys_quanyi_state"
              :key="dict.value"
              :label="dict.value"
            >{{generateTitle(dict.label)}}</el-radio>
          </el-radio-group>
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">{{$t('youhuijuanquanyi.确定')}}</el-button>
        <el-button @click="cancel">{{$t('youhuijuanquanyi.取消')}}</el-button>
      </div>
    </el-dialog>

    <el-dialog
      :title="$t('youhuijuanquanyi.选择商家')"
      :visible.sync="showMerchantDialog"
      width="900px"
      append-to-body
    >
      <!-- 搜索表单 -->
      <el-form :inline="true" :model="merchantQueryParams" size="small" class="demo-form-inline">
        <el-form-item :label="$t('infoussanhuser.用户名')">
          <el-input v-model="merchantQueryParams.userName" :placeholder="$t('infoussanhuser.请输入用户名')" clearable />
        </el-form-item>
        <el-form-item :label="$t('infoussanhuser.手机号码')">
          <el-input v-model="merchantQueryParams.telPhone" :placeholder="$t('infoussanhuser.请输入手机号码')" clearable />
        </el-form-item>
        <el-form-item :label="$t('infoussanhuser.商家名称')">
          <el-input v-model="merchantQueryParams.nickName" :placeholder="$t('infoussanhuser.请输入商家名称')" clearable />
        </el-form-item>
        <el-form-item :label="$t('infoussanhuser.用户邮箱')">
          <el-input v-model="merchantQueryParams.email" :placeholder="$t('infoussanhuser.请输入用户邮箱')" clearable />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleMerchantSearch">{{$t('infoussanhuser.搜索')}}</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetMerchantQuery">{{$t('infoussanhuser.重置')}}</el-button>
        </el-form-item>
      </el-form>
      <!-- 商家表格 -->
      <el-table
        :data="merchantList"
        v-loading="merchantLoading"
        highlight-current-row
        @current-change="handleMerchantSelect"
        style="width: 100%; margin-top: 10px;"
      >
        <el-table-column prop="userId" :label="$t('infoussanhuser.用户ID')" width="80"/>
        <el-table-column prop="nickName" :label="$t('infoussanhuser.商家名称')"/>
        <el-table-column prop="telPhone" :label="$t('infoussanhuser.手机号码')"/>
        <el-table-column prop="email" :label="$t('infoussanhuser.用户邮箱')"/>
        <el-table-column :label="$t('infoussanhuser.帐号状态')" align="center" prop="status">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.status==0" type="primary">{{generateTitle('正常')}}</el-tag>
            <el-tag v-if="scope.row.status==1" type="danger">{{generateTitle('暂停')}}</el-tag>
          </template>
        </el-table-column>
        <el-table-column :label="$t('infoussanhuser.审核状态')" align="center" prop="auditStatus">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.auditStatus==0" type="info" effect="dark">{{generateTitle('未审核')}}</el-tag>
            <el-tag v-if="scope.row.auditStatus==1" type="primary" effect="dark">{{generateTitle('已审核')}}</el-tag>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <pagination
        v-show="merchantTotal>0"
        :total="merchantTotal"
        :page.sync="merchantQueryParams.pageNum"
        :limit.sync="merchantQueryParams.pageSize"
        @pagination="loadMerchantList"
        @size-change="handleMerchantSizeChange"
        @current-change="handleMerchantPageChange"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitMerchant">{{$t('youhuijuanquanyi.确定')}}</el-button>
        <el-button @click="showMerchantDialog = false">{{$t('youhuijuanquanyi.取消')}}</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listUser, getUser, delUser, addUser, updateUser } from "@/api/infouser/user";

import { listQuanyi, getQuanyi, delQuanyi, addQuanyi, updateQuanyi,getStoreList } from "@/api/system/sjquanyi";
import {generateTitle} from '../../../utils/i18.js'
import Bus from '../../../utils/Bus.js'
export default {
  name: "Quanyi",
  dicts: ['sys_vip_youhui', 'sys_quanyi_state','sys_vip_zuany'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // quanyi表格数据
      quanyiList: [],
      // 弹出层标题
      title: "",
      language:'',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        type:"2",
        vip: null,
        yhfangs: null,
        yhnum: null,
        name: null,
        shuoming: null,
        tiaojian: null,
        num: null,
        language:null,

      },
      // 表单参数
      form: {edit:true},
      // 表单校验
      rules: {

        vip: [
          { required: true, message: this.$t('youhuijuanquanyi.是否会员可用不能为空'), trigger: "change" }
        ],
        yhfangs: [
          { required: true, message: this.$t('youhuijuanquanyi.优惠方式不能为空'), trigger: "change" }
        ],
        yhnum: [
          { required: true, message: this.$t('youhuijuanquanyi.优惠折扣不能为空'), trigger: "blur" },
          {
            validator: (rule, value, callback) => {
              // 当不是运费优惠(yhfangs≠1)时检查是否>0
              if (this.form.yhfangs != 1 && value <= 0) {
                callback(new Error(this.$t('youhuijuanquanyi.值必须大于0')));
              } else {
                callback();
              }
            },
            trigger: 'blur'
          }
        ],
        name: [
          { required: true, message: this.$t('youhuijuanquanyi.优惠券名称不能为空'), trigger: "blur" }
        ],
        num: [
          { required: true, message: this.$t('youhuijuanquanyi.每月会员可用次数不能为空'), trigger: "blur" }
        ],
        total: [
          { required: true, message: this.$t('youhuijuanquanyi.优惠券总数不能为空'), trigger: "blur" }
        ],
        validity: [
          { required: true, message: this.$t('youhuijuanquanyi.优惠券有效期不能为空'), trigger: "blur" }

        ],
        lqxz:[
          { required: true, message: this.$t('youhuijuanquanyi.每人领取数量不能为空'), trigger: "blur" }
        ],
        state:[
          { required: true, message: this.$t('youhuijuanquanyi.请选择状态'), trigger: "blur" }
        ],
        merchantName:[
          { required: true, message: this.$t('youhuijuanquanyi.商家不能为空'), trigger: "change" }
        ],
        shId: [
          { required: true, message: this.$t('youhuijuanquanyi.店铺不能为空'), trigger:"change"}
        ]
      },
      showMerchantDialog: false,
      merchantQueryParams: {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        telPhone: null,
        nickName: null,
        email: null,
        status:'0',
        auditStatus: '1'
      },
      merchantList: [],
      storeList:[],
      storeLoading:false,
      merchantTotal: 0,
      merchantLoading: false,
      selectSj:null, //选择的商家
    };
  },
  created() {
    this.language =localStorage.getItem('lang')
    this.getList();
  },
  mounted() {
    // 确保Bus监听已建立
    Bus.$on('l18zh', (res) => {
      this.language = res;
      this.getList();
    })
  },
  methods: {
    generateTitle,
    /** 查询quanyi列表 */
    getList() {
      this.loading = true;
      this.queryParams.language= this.language=='zh_CN'?'2':this.language=='zh_TW'?'3':this.language=='en_US'?'1':'0';
      listQuanyi(this.queryParams).then(response => {
        this.quanyiList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        vip: null,
        yhfangs: null,
        yhnum: null,
        name: null,
        shuoming: null,
        tiaojian: null,
        num: null,
        state:null,
        total:null,
        validity:null,
        lqxz:null,
        language:null,
        edit:true,
        merchantName:null,
        merchantId:null,
        shId:null,
        type:'2',
      };
      this.selectSj=null;
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = this.$t('youhuijuanquanyi.添加优惠券');
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getQuanyi(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = this.$t('youhuijuanquanyi.修改优惠券');
        this.getStoreList(this.form.merchantId);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateQuanyi(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('youhuijuanquanyi.修改成功'));
              this.open = false;
              this.getList();
            });
          } else {
            this.form.language= this.language=='zh_CN'?'2':this.language=='zh_TW'?'3':this.language=='en_US'?'1':'0';
            addQuanyi(this.form).then(response => {
              this.$modal.msgSuccess(this.$t('youhuijuanquanyi.新增成功'));
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm(this.$t('youhuijuanquanyi.是否确认删除编号为') + ids + this.$t('youhuijuanquanyi.的数据项')).then(function() {
        return delQuanyi(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(this.$t('youhuijuanquanyi.删除成功'));
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/quanyi/export', {
        ...this.queryParams
      }, `quanyi_${new Date().getTime()}.xlsx`)
    },
     // 加载商家列表
     loadMerchantList() {
      this.merchantLoading = true;
      // 这里调用和sjuser.vue一样的API
      listUser({
        ...this.merchantQueryParams,
        userType: 1 // 只查商家
      }).then(res => {
        this.merchantList = res.rows;
        this.merchantTotal = res.total;
        this.merchantLoading = false;
      });
    },
    // 搜索
    handleMerchantSearch() {
      this.merchantQueryParams.pageNum = 1;
      this.loadMerchantList();
    },
    // 重置
    resetMerchantQuery() {
      this.merchantQueryParams = {
        pageNum: 1,
        pageSize: 10,
        userName: null,
        telPhone: null,
        nickName: null,
        email: null,
        auditStatus: null
      };
      this.loadMerchantList();
    },
    // 分页
    handleMerchantPageChange(page) {
      this.merchantQueryParams.pageNum = page;
      this.loadMerchantList();
    },
    handleMerchantSizeChange(size) {
      this.merchantQueryParams.pageSize = size;
      this.loadMerchantList();
    },

    // 选择商家
    handleMerchantSelect(row) {
      console.log('11')
      console.log(row);
      this.selectSj=row;
      // this.form.merchantId = row.userId;
      // this.form.merchantName = row.nickName;
      // this.showMerchantDialog = false;
    },
    submitMerchant() {
      console.log('55')
      console.log(this.selectSj);
      if (this.selectSj?.userId) {
        this.form.merchantId = this.selectSj.userId;
        this.form.merchantName = this.selectSj.nickName;
        this.showMerchantDialog = false;
        this.getStoreList(this.form.merchantId);
        this.form.shId=null;
      }else{
        this.$modal.msgError(this.$t('youhuijuanquanyi.请选择商家'));
        return
      }
    },
    getStoreList(id) {
      return getStoreList(id).then(res => {
        this.storeList = res.data;
      })
    }
  },
  watch: {
    showMerchantDialog(val) {
      if (val) this.loadMerchantList();
    }
  }

};
</script>
