<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <!--省市区（与学校关联）、学校、高考年份、班级、-->
      <el-form-item label="省" prop="pro">
        <el-select v-model="queryParams.pro" placeholder="请选择省" clearable size="small" @change="changePro">
          <el-option v-for="dict in proList" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="市" prop="city">
        <el-select v-model="queryParams.city" placeholder="请选择市" clearable size="small" @change="changeCity">
          <el-option v-for="dict in cityList" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="区" prop="area">
        <el-select v-model="queryParams.area" placeholder="请选择区" clearable size="small" @change="getSchoolList">
          <el-option v-for="dict in areaList" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="学校" prop="schoolId">
        <el-select v-model="queryParams.schoolId" placeholder="请选择市" clearable size="small">
          <el-option v-for="item in schoolList" :key="item.id" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item label="学校" prop="schoolName">
        <el-input v-model="queryParams.schoolName" placeholder="请输入学校" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="单招年份" prop="endYear">
        <el-input v-model="queryParams.endYear" placeholder="请输入单招年份" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="班级" prop="className">
        <el-input v-model="queryParams.className" placeholder="请输入班级" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!--代理商、卡号段、学生姓  名、手机、-->
      <el-form-item label="代理商" prop="agentName">
        <el-input v-model="queryParams.agentName" placeholder="请输入代理商" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>

      <el-form-item label="卡号段" prop="startCard">
        <el-input v-model="queryParams.startCard" style="width:120px" placeholder="起始卡号" clearable size="small" @keyup.enter.native="handleQuery" />
        -
        <el-input v-model="queryParams.endCard" style="width:120px" placeholder="结束卡号" clearable size="small" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="学生姓名" prop="name">
        <el-input v-model="queryParams.name" placeholder="请输入学生姓名" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="学生手机" prop="mobile">
        <el-input v-model="queryParams.mobile" placeholder="请输入学生手机" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!--卡类型、卡状态、缴费状态、-->
      <el-form-item label="卡类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择卡类型" clearable>
          <el-option v-for="dict in dict.type.card_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="卡状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择卡状态" clearable>
          <el-option v-for="dict in dict.type.card_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="缴费状态" prop="payStatus">
        <el-select v-model="queryParams.payStatus" placeholder="请选择缴费状态" clearable>
          <el-option v-for="dict in dict.type.pay_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <!--开卡时间、缴费时间-->
      <el-form-item label="开卡时间" prop="distributeTime">
        <el-date-picker clearable v-model="distributeTimes" style="width:220px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" placeholder="请选择开卡时间" />
      </el-form-item>
      <el-form-item label="缴费时间" prop="payTime">
        <el-date-picker clearable v-model="payTimes" style="width:220px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" placeholder="请选择缴费时间" />
      </el-form-item>
      <el-form-item label="分配类别">
        <el-select v-model="queryParams.distributeExamType">
          <el-option value="" label="不限" />
          <el-option v-for="t in examTypes" :key="t" :value="t" :label="t" />
        </el-select>
      </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>
    <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="['voluntary:busiCards:add']">制卡</el-button>
      </el-col>
      <el-col :span="1.5" v-if="false">
        <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['voluntary:busiCards:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5" v-if="false">
        <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete" v-hasPermi="['voluntary:busiCards:remove']">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain size="mini" :disabled="multiple" @click="handleBatch('pay', '缴费')" v-hasPermi="['voluntary:busiCards:pay']">缴费</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain size="mini" :disabled="multiple" @click="handleBatch('close', '关卡')" v-hasPermi="['voluntary:busiCards:close']">关卡</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain size="mini" :disabled="multiple" @click="handleBatch('reopen', '重开')" v-hasPermi="['voluntary:busiCards:reopen']">重开</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain size="mini" :disabled="multiple" @click="handleBatch('delay', '续期')" v-hasPermi="['voluntary:busiCards:delay']">续期</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="success" plain size="mini" :disabled="multiple" @click="handleBatch('refund', '退费')" v-hasPermi="['voluntary:busiCards:refund']">退费</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport" v-hasPermi="['voluntary:busiCards:export']">导出</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-set-up" size="mini" @click="handleBatchRegister" v-hasPermi="['voluntary:busiCards:register']">批量注册</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-table v-loading="loading" :data="busiCardsList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="账号" align="center" prop="cardNo" width="120" />
      <el-table-column label="密码" align="center" prop="password" width="120" />
      <el-table-column label="卡类型" align="center" prop="type">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.card_type" :value="scope.row.type" />
        </template>
      </el-table-column>
      <el-table-column label="学校" align="center" prop="schoolName" width="120" class-name="school-cell">
        <template #default="{row}">
          <template v-if="row.schoolId>0">{{row.schoolName}}</template>
          <el-badge v-else-if="row.schoolId<0" type="success" value="其它">{{row.customSchoolName}}</el-badge>
        </template>
      </el-table-column>
      <el-table-column label="姓名_手机" align="center" prop="nameMobile" width="180" />
      <el-table-column label="单招年份" align="center" prop="endYear" />
      <el-table-column label="班级" align="center" prop="className" />
      <el-table-column label="班级(新)" align="center" prop="customClassName" />
      <el-table-column label="代理商" align="center" prop="agentName" />
      <el-table-column label="分配省份" align="center" prop="distributeLocation" width="80" />
      <el-table-column label="分配学校" align="center" prop="distributeSchoolName" width="120" />
      <el-table-column label="分配类别" align="center" prop="distributeExamType" width="80" />
      <el-table-column label="卡状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.card_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="缴费状态" align="center" prop="payStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pay_status" :value="scope.row.payStatus" />
        </template>
      </el-table-column>
      <el-table-column label="开卡时间" align="center" prop="distributeTime" width="160" />
      <el-table-column label="激活时间" align="center" prop="activeTime" width="160" />
      <el-table-column label="到期时间" align="center" prop="outDate" width="160" />
      <el-table-column label="缴费时间" align="center" prop="payTime" width="160" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="200">
        <template slot-scope="scope">
          <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['voluntary:busiCards:edit']">修改</el-button>
          <el-button size="mini" type="text" icon="el-icon-refresh" @click="handleResetPwd(scope.row)" v-hasPermi="['voluntary:busiCards:resetpwd']">重置密码</el-button>
          <el-button v-if="false" size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)" v-hasPermi="['voluntary:busiCards: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-dialog title="制卡" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="卡类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择卡状态">
            <el-option v-for="dict in dict.type.card_type" :key="dict.value" :label="dict.label" :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数量" prop="cardNum">
          <el-input v-model.number="form.cardNum" placeholder="请输入数量" />
        </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>
    <card-edit ref="edit" @refresh="getList" />
    <el-dialog title="批量注册" :visible.sync="showBatchRegister" width="500px" append-to-body>
      <el-form ref="batchRegisterForm" :model="batchRegisterParams" :rules="batchRegisterRules" label-width="80px">
        <el-form-item label="起始卡号" prop="startCardNo">
          <el-input v-model="batchRegisterParams.startCardNo" />
        </el-form-item>
        <el-form-item label="结束卡号" prop="endCardNo">
          <el-input v-model="batchRegisterParams.endCardNo" />
        </el-form-item>
        <el-form-item label="注册省份" prop="location">
          <el-select v-model="batchRegisterParams.location" filterable clearable>
            <el-option v-for="pro in proList" :key="pro.id" :value="pro.sname" :label="pro.sname" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="batchRegistering" @click="submitBatchRegister">确 定</el-button>
        <el-button @click="showBatchRegister=false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import cardEdit from './edit'
import {
  listBusiCards,
  getBusiCards,
  batchUpdate,
  delBusiCards,
  addBusiCards,
  updateBusiCards,
  batchRegisterCards,
  getExamTypes
} from "@/api/voluntary/busiCards";
import { locationList } from "@/api/voluntary/sysLocations";
import { listBusiSchools } from "@/api/voluntary/busiSchools";
export default {
  name: "BusiCards",
  dicts: ['card_status', 'bool_flag', 'card_type', 'pay_status'],
  components: { cardEdit },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      proList: [],
      cityList: [],
      areaList: [],
      schoolList: [],
      // 总条数
      total: 0,
      // vip卡表格数据
      busiCardsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        pro: null,
        city: null,
        area: null,
        schoolName: null,
        endYear: null,
        className: null,
        agentName: null,
        startCard: null,
        endCard: null,
        name: null,
        mobile: null,
        type: null,
        status: null,
        payStatus: null,
        distributeExamType: ''
      },
      distributeTimes: [],
      payTimes: [],
      examTypes: [],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        nickName: [
          { required: true, message: "用户姓名不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "卡状态0未注册，1激活卡，2缴费卡，3过期卡，4退费卡，5已关卡不能为空", trigger: "change" }
        ],
        isPay: [
          { required: true, message: "是否付费不能为空", trigger: "change" }
        ],
        isSettlement: [
          { required: true, message: "是否结算不能为空", trigger: "change" }
        ],
        isUsed: [
          { required: true, message: "是否使用不能为空", trigger: "change" }
        ],
        createTime: [
          { required: true, message: "生成时间不能为空", trigger: "blur" }
        ],
      },
      // batch register
      showBatchRegister: false,
      batchRegistering: false,
      batchRegisterParams: {
        startCardNo: '',
        endCardNo: '',
        location: ''
      },
      batchRegisterRules: {
        startCardNo: [{required: true, message: "起始卡号不能为空"}],
        endCardNo: [{required: true, message: "结束卡号不能为空"}],
        location: [{required: true, message: "省份不能为空"}]
      }
    };
  },
  created() {
    // 获取省
    this.getExamTypes()
    this.getAreaList(1, 'proList');
    this.getList();
  },
  methods: {
    async getExamTypes() {
      const res = await getExamTypes()
      this.examTypes = res.data
    },
    changePro(event) {
      this.queryParams.city = '';
      this.queryParams.area = '';
      this.cityList = [];
      this.areaList = [];
      this.getAreaList(event, "cityList");
    },
    changeCity(event) {
      this.queryParams.area = '';
      this.areaList = [];
      this.getAreaList(event, "areaList");
    },
    /** 查询省市区 */
    getAreaList(parentId, obj) {
      let vm = this;
      locationList({ parentId: parentId }).then(response => {
        vm[obj] = response.data;
      });
    },
    getSchoolList() {
      let vm = this, { pro, area, city } = this.queryParams;
      this.schoolsList = [];
      if (pro && area && city) {
        listBusiSchools({ pageSize: 100, pro, area, city }).then(res => {
          vm.schoolList = res.rows || []
        });
      }
    },
    /** 查询vip卡列表 */
    getList() {
      this.loading = true;
      this.addDateRange(this.queryParams, this.distributeTimes, 'DistributeTime')
      this.addDateRange(this.queryParams, this.payTimes, 'PayTime')
      listBusiCards(this.queryParams).then(response => {
        this.busiCardsList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        cardId: null,
        cardNo: null,
        nickName: null,
        schoolId: null,
        distributeSchoolId: null,
        gradeId: null,
        classId: null,
        year: null,
        agentId: null,
        password: null,
        cardNum: null,
        status: null,
        type: null,
        isPay: null,
        isRefund: null,
        isSettlement: null,
        isUsed: null,
        closeId: null,
        openId: null,
        remark: null,
        distributeTime: null,
        outDate: null,
        payTime: null,
        activeTime: null,
        refundTime: null,
        closeTime: null,
        createTime: null,
        updateTime: 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.cardId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加vip卡";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$refs.edit.open(row);
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.cardId != null) {
            updateBusiCards(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addBusiCards(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /**批量操作 */
    async handleBatchRegister() {
      this.showBatchRegister = true
    },
    async submitBatchRegister() {
      await this.$refs.batchRegisterForm.validate()
      this.batchRegistering = true
      await batchRegisterCards(this.batchRegisterParams).finally(()=> this.batchRegistering = false)
      this.showBatchRegister = false
      this.$message.success('操作成功')
      this.resetForm('batchRegisterForm')
    },
    async handleBatch(command, title) {
      const cardIds = this.ids;
      let data = { command, cardIds };
      if (command == 'delay') {
        this.$modal.prompt('请输入需要续期天数!').then(({ value }) => {
          if (value && parseInt(value)) {
            data.days = parseInt(value);
            return batchUpdate(data);
          } else {
            this.$modal.msgError(`数据格式不对!`);
            throw "数据格式不对!";
          }
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess(`${title}成功`);
        }).catch(() => { });
      } else {
        this.$modal.confirm(`是否确认${title}vip卡编号为${cardIds}的数据项？`).then(function () {
          return batchUpdate(data);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess(`${title}成功`);
        }).catch(() => { });
      }
    },
    handleResetPwd(row) {
      this.$modal.prompt('请输入新密码!').then(({ value }) => {
        if (value) {
          return updateBusiCards({ cardId: row.cardId, password: value });
        } else {
          this.$modal.msgError(`新密码不能为空!`);
          throw "数据格式不对!";
        }
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess(`重置密码成功`);
      }).catch(() => { });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const cardIds = row.cardId || this.ids;
      this.$modal.confirm('是否确认删除vip卡编号为"' + cardIds + '"的数据项？').then(function () {
        return delBusiCards(cardIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('voluntary/busiCards/export', {
        ...this.queryParams
      }, `busiCards_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>

<style scoped>
::v-deep .el-table .school-cell .cell {
  overflow: visible;
}
</style>
