<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="标题" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
       <el-form-item label="有效期" prop="limitTime">
                 <el-date-picker v-model="limitTime" size="small" style="width: 220px" value-format="yyyy-MM-dd" type="daterange" range-separator="-" start-placeholder="开始日期" end-placeholder="结束日期" @change="change"></el-date-picker>
       </el-form-item>
      <el-form-item label="券类型" prop="couponType">
        <el-select v-model="queryParams.couponType" placeholder="请选择券类型" clearable size="small">
          <el-option
            v-for="dict in couponTypeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="面额" prop="price">
        <el-input
          v-model="queryParams.price"
          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>

    <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="['his:coupon:add']"
        >新增</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="['his:coupon:edit']"
        >修改</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="['his:coupon:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['his:coupon:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" border :data="couponList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="优惠券名称" align="center" prop="title" width="120px"/>
      <el-table-column label="面额" align="center" prop="price" />
      <el-table-column label="折扣" align="center" prop="rate" />
      <el-table-column label="数量" align="center" prop="number" />
      <el-table-column label="卷类型 " align="center" prop="couponType" width="120px">
        <template slot-scope="scope">
          <dict-tag :options="couponTypeOptions" :value="scope.row.couponType"/>
        </template>
      </el-table-column>
     <el-table-column label="状态" align="center" prop="status">
       <template slot-scope="scope">
         <dict-tag :options="statusOptions" :value="scope.row.status"/>
       </template>
     </el-table-column>
      <el-table-column label="最低消费金额可用" align="center" prop="minPrice" />
      <el-table-column label="剩余数量" align="center" prop="remainNumber" />
      <el-table-column label="有效期" align="center" prop="limitTime" width="180"/>
      <el-table-column label="创建时间" align="center" prop="createTime" width="180"/>
      <el-table-column label="更改时间" align="center" prop="updateTime" width="180"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="150px">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['his:coupon:edit']"
          >修改</el-button>
          <el-button
               size="mini"
               type="text"
               @click="handledetails(scope.row)"
           >详情

          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['his:coupon:remove']"
          >删除</el-button>

         <el-button
               size="mini"
               type="text"
               @click="send(scope.row)"
               v-hasPermi="['his:userCoupon:send']"
           >发送优惠劵
          </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="openSend" width="500px" append-to-body>
      <el-form ref="formSend"  label-width="100px">

        <el-form-item label="优惠券名称" prop="title">
          <div style="margin-left: 20px;font-weight: bold;">    {{sendForm.title}}</div>

        </el-form-item>
        <el-form-item label="面额" prop="price" v-if="form.couponType==1">
          <div style="margin-left: 20px;font-weight: bold;">   {{sendForm.price}}</div>
        </el-form-item>
        <el-form-item label="搜索用户" >
          <el-input placeholder="输入电话号码查询用户" v-model="phone" class="input-with-select">
              <el-button slot="append" icon="el-icon-search" @click="selectPhone"></el-button>
            </el-input>
        </el-form-item>
       <el-form-item label="用户" >
         <el-select v-model="sendForm.userId">
              <el-option
                v-for="item in userList"
                :key="item.name"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
       </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitSendForm">发 送</el-button>
        <el-button @click="cancelSend">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改优惠券对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="优惠券名称" prop="title">
          <el-input v-model="form.title" placeholder="请输入优惠券名称" />
        </el-form-item>

        <el-form-item label="过期时间" prop="limitTime">
          <el-date-picker clearable size="small"
            v-model="form.limitTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择过期时间">
          </el-date-picker>
        </el-form-item>


        <el-form-item label="用户可领取数量" prop="limitCount" >
          <el-input-number v-model="form.limitCount"  :min="1"  label="请输入用户可领取数量"></el-input-number>
        </el-form-item>
        <el-form-item label="卷类型" prop="couponType">
          <el-select v-model="form.couponType" placeholder="请选择卷类型" @change="isShowChange">
            <el-option
              v-for="dict in couponTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="可用分类" prop="cateIds" v-show="form.couponType==5||form.couponType==6">
          <el-select v-model="form.cateIds" multiple placeholder="请选择可用分类">
            <el-option
              v-for="dict in cateIdsOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="面额" prop="price" v-if="form.couponType==1||form.couponType==5||form.couponType==6">
          <el-input-number v-model="form.price"  :min="0"  label="请输入面额"></el-input-number>
        </el-form-item>
        <el-form-item label="最低消费" prop="minPrice" v-if="form.couponType==1||form.couponType==5||form.couponType==6">
           <el-input-number v-model="form.minPrice"  :min="0"  label="请输入最低消费金额可用"></el-input-number>
        </el-form-item>
        <el-form-item label="打折百分比" prop="rate" v-if="form.couponType==4">
          <el-input-number v-model="form.rate"  :min="1" :max="100"  label="请输入折扣百分比"></el-input-number>
        </el-form-item>

        <el-form-item label="有效期类型" prop="limitType">
          <el-select v-model="form.limitType" placeholder="请选择有效期类型">
            <el-option
              v-for="dict in limitTypeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>

        <el-form-item label="领取后有效期(天)" prop="limitDay" >
          <el-input-number v-model="form.limitDay"  :min="1"  label="请输入领取后有效期"></el-input-number>
        </el-form-item>
        <el-form-item label="数量" prop="number">
            <el-input-number v-model="form.number"  :min="0"  label="请输入数量"></el-input-number>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
                   <el-radio :label="item.dictValue" v-for="item in statusOptions" >{{item.dictLabel}}</el-radio>
          </el-radio-group>
        </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
    	:with-header="false"
            size="75%"
             :title="show.title" :visible.sync="show.open">
         <couponDetails  ref="Details" />
       </el-drawer>
  </div>
</template>

<script>
import { listCoupon, getCoupon, delCoupon, addCoupon, updateCoupon, exportCoupon } from "@/api/his/coupon";
import { sendCoupon } from "@/api/his/userCoupon";
import couponDetails from '../../components/his/couponDetails.vue';
import {getUserList} from "@/api/his/doctor";
import {selectUser} from "@/api/his/user";
import {getAllCateList} from "@/api/his/packageCate";
export default {
  name: "Coupon",
  components: { couponDetails },
  data() {
    return {
      show:{
              open:false,
            },
      limitTime:[],
      userList:[],
      userName: null,
      // 遮罩层
      loading: true,
      phone:null,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 优惠券表格数据
      couponList: [],
      statusOptions: [],
      limitTypeOptions: [],
      privateTypeOptions: [],
      diseaseTypeOptions: [],
      orOptions: [],
      cateIdsOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      openSend:false,
      // 卷类型 1代金券 字典
      couponTypeOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        limitTime: null,
        price: null,
        number: null,
        couponType: null,
        minPrice: null,
        remainNumber: null,
        sTime:null,
        eTime:null
      },
      sendForm:{
        title: null,
        price: null,
        couponId:null,
        couponType:null,
        userId:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: "标题不能为空", trigger: "blur" }
        ],
        limitTime: [
          { required: true, message: "有效期不能为空", trigger: "blur" }
        ],
        couponType: [
          { required: true, message: "券类型不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    getAllCateList().then(response => {
      this.diseaseTypeOptions = response.data.diseaseType;
      this.privateTypeOptions = response.data.privateType;
    });
    this.getDicts("sys_coupon_type").then(response => {
      this.couponTypeOptions = response.data;
    });
    this.getDicts("sys_company_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("sys_coupon_limit_type").then(response => {
      this.limitTypeOptions = response.data;
    });
    this.getDicts("sys_company_or").then(response => {
      this.orOptions = response.data;
    });

  },
  methods: {
    send(row){
      this.openSend=true;
      this.sendForm.userId=null;
      this.sendForm.couponId=row.couponId;
      this.sendForm.title=row.title;
      this.sendForm.price=row.price;
      this.sendForm.couponType=row.couponType;
    },
    selectPhone(){
        selectUser(this.phone).then(response => {
          this.userList=response.rows;
          if(this.userList!=null){
              this.sendForm.userId=this.userList[0].id;
          }
        });
    },
    cancelSend(){
      this.openSend=false;
    },
    submitSendForm(row){
      if(this.sendForm.userId==null){
        return this.$message('未选择用户');
      }
      sendCoupon(this.sendForm).then(response => {
        this.msgSuccess("发送成功");
        this.openSend=false;
        this.getList();
      });

    },
    /** 查询优惠券列表 */
    getList() {
      this.loading = true;
      listCoupon(this.queryParams).then(response => {
        this.couponList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        couponId: null,
        title: null,
        createTime: null,
        limitTime: null,
        price: null,
        number: null,
        couponType: null,
        minPrice: null,
        remainNumber: null,
        status:"1",
        rate:0,
        limitDay:1,
        limitCount:1,
        limitType:null,
        cateIds:null,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
       this.limitTime=null;
      this.queryParams.sTime=null;
      this.queryParams.eTime=null;
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.couponId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    handledetails(row){
            this.show.open=true;
            setTimeout(() => {
                 this.$refs.Details.getDetails(row.couponId);
            }, 1);
     },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加优惠券";
    },
    isShowChange(){
      this.form.cateIds=null
      if(this.form.couponType==5){
        this.cateIdsOptions=this.privateTypeOptions;
      }else{
        this.cateIdsOptions=this.diseaseTypeOptions;
      }

    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const couponId = row.couponId || this.ids
      getCoupon(couponId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改优惠券";
        this.form.status=String(this.form.status)
        this.form.isShow=String(this.form.isShow)

          if(this.form.couponType==5){
            this.cateIdsOptions=this.privateTypeOptions;
          }else{
            this.cateIdsOptions=this.diseaseTypeOptions;
          }
          if(this.form.cateIds!=null){
           this.form.cateIds= JSON.parse(this.form.cateIds)
          }

      });
    },
    /** 提交按钮 */
    submitForm() {

      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.form.cateIds!=null){
           this.form.cateIds= JSON.stringify(this.form.cateIds)
          }

          if (this.form.couponId != null) {
            updateCoupon(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addCoupon(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    change(){
          if(this.limitTime!=null){
            this.queryParams.sTime=this.limitTime[0];
            this.queryParams.eTime=this.limitTime[1];
          }else{
            this.queryParams.sTime=null;
            this.queryParams.eTime=null;
          }

        },
    /** 删除按钮操作 */
    handleDelete(row) {
      const couponIds = row.couponId || this.ids;
      this.$confirm('是否确认删除优惠券编号为"' + couponIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCoupon(couponIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有优惠券数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportCoupon(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
