<template>
  <div id="coupon_manage" v-loading="loading" :element-loading-text="loadingText">
    <div style="display: flex; margin-bottom: 10px">
      <el-input style="width: 300px" prefix-icon="el-icon-search" v-model="couponTitle" clearable
                placeholder="请输入优惠券标题"></el-input>
      <!--      <el-select v-model="transactionStatus" placeholder="请选择交易状态" style="margin-left: 10px">-->
      <!--        <el-option-->
      <!--            v-for="item in transactionStatusList"-->
      <!--            :key="item.value"-->
      <!--            :label="item.label"-->
      <!--            :value="item.value">-->
      <!--        </el-option>-->
      <!--      </el-select>-->
      <el-button style="margin-left: 10px" type="primary" v-on:click="getSearchCoupon">搜索</el-button>
      <el-button style="margin-left: 10px" type="primary" v-on:click="couponShow">新增</el-button>
      <el-button style="margin-left: 10px" type="primary" v-on:click="handleDownloadTemplate">Excel导入模版下载</el-button>
    </div>
    <div>
      <el-table
          :data="couponList"
          border
          :height="tableHeight">
        <el-table-column
            prop="title"
            label="优惠券标题"
            width="150">
        </el-table-column>
        <el-table-column
            prop="type"
            label="类型"
            width="60"
            :formatter="getCouponType">
        </el-table-column>
        <el-table-column
            prop="amount"
            label="优惠的金额"
            width="100">
        </el-table-column>
        <el-table-column
            prop="meetAmount"
            label="满足的金额"
            width="100">
        </el-table-column>
        <el-table-column
            prop="expiryType"
            label="有效期类型"
            width="100"
            :formatter="getDateType">
        </el-table-column>
        <el-table-column
            prop="beginDate"
            label="开始日期"
            width="90">
        </el-table-column>
        <el-table-column
            prop="endDate"
            label="结束日期"
            width="90">
        </el-table-column>
        <el-table-column
            prop="delayDays"
            label="天数"
            width="60">
        </el-table-column>
        <el-table-column
            prop="availableProduct"
            label="可用产品"
            width="120"
            :formatter="getRangeType">
        </el-table-column>
        <el-table-column
            prop="availableChannel"
            label="可用平台"
            width="120"
            :formatter="getPlatformType">
        </el-table-column>
        <el-table-column
            prop="availableChannelMemo"
            label="可用平台渠道说明"
            width="150"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            prop="remark"
            label="备注"
            width="120"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            prop="keyWord"
            label="减免服务的关键字"
            width="120"
            show-overflow-tooltip>
        </el-table-column>
        <el-table-column
            fixed="right"
            prop="enable"
            label="是否有效"
            width="90">
          <template slot-scope="scope">
            <el-switch
                v-on:change="statusChange(scope.row.couponId, scope.row.enable)"
                v-model="scope.row.enable"
                active-color="#13ce66"
                inactive-color="#ff4949">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column
            fixed="right"
            label="操作"
            align="center"
            width="200"
        >
          <template slot-scope="scope">
            <input
                ref="uploadExcel-input"
                style="display: none"
                type="file"
                accept=".xlsx, .xls"
                @change="handkeFileChange"
            />
            <el-button v-if="scope.row.enable === true" @click="getCompanyShow(scope.row)" type="primary">发放</el-button>
            <el-button v-if="scope.row.enable === true" type="primary" @click="handleImportExcel(scope.row)">
              Excel导入分发
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="display: flex; justify-content: flex-end; margin-top: 10px">
      <el-pagination
          @size-change="getNumberPage"
          @current-change="getPageNumber"
          :current-page.sync="pageNumber"
          :page-sizes="[10, 30, 50, 100]"
          :page-size="numberPage"
          layout="total, sizes, prev, pager, next"
          :total="totalPage">
      </el-pagination>
    </div>
    <el-dialog
        title="优惠券信息"
        :visible.sync="isShow"
        width="50%"
        :before-close="couponClose">
      <div style="display: flex; flex-direction: column">
        <div style="display: flex">
          <div style="display: flex; flex: 1; align-items: center; justify-content: flex-end">
            <span style="text-align: right"><span style="color: red">*</span>优惠券标题：</span>
            <el-input style="width: 200px" v-model="title" placeholder="请输入优惠券标题"></el-input>
          </div>
          <div style="display: flex; flex: 1; align-items: center; justify-content: flex-end">
            <span style="text-align: right"><span style="color: red">*</span>优惠券类型：</span>
            <el-select v-model="couponType" placeholder="请选择优惠券类型" style="width: 200px">
              <el-option
                  v-for="item in couponTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
        <div style="display: flex; margin-top: 5px">
          <div style="display: flex; flex: 1; align-items: center; justify-content: flex-end">
            <span style="text-align: right"><span style="color: red">*</span>优惠的金额：</span>
            <el-input style="width: 200px" v-model="amount" placeholder="请输入优惠的金额"></el-input>
          </div>
          <div style="display: flex; flex: 1; align-items: center; justify-content: flex-end">
            <span style="text-align: right"><span style="color: red">*</span>需要满足的金额：</span>
            <el-input style="width: 200px" v-model="meetAmount" placeholder="请输入需要满足的金额"></el-input>
          </div>
        </div>
        <div style="display: flex; margin-top: 5px">
          <div style="display: flex; flex: 1; align-items: center; justify-content: flex-end">
            <span style="text-align: right"><span style="color: red">*</span>有效期类型：</span>
            <el-select v-model="dateType" placeholder="请选择有效期类型" style="width: 200px" v-on:change="dateTypeChange">
              <el-option
                  v-for="item in dateTypeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div style="display: flex; flex: 1; align-items: center; justify-content: flex-end">
          </div>
        </div>
        <div style="display: flex; margin-top: 5px" v-if="dateType === '1'">
          <div style="display: flex; flex: 1; align-items: center; justify-content: flex-end">
            <span style="text-align: right"><span style="color: red">*</span>开始日期：</span>
            <el-date-picker
                style="width: 200px"
                v-model="beginDate"
                type="date"
                placeholder="选择开始日期">
            </el-date-picker>
          </div>
          <div style="display: flex; flex: 1; align-items: center; justify-content: flex-end">
            <span style="text-align: right"><span style="color: red">*</span>结束日期：</span>
            <el-date-picker
                style="width: 200px"
                v-model="endDate"
                type="date"
                placeholder="选择结束日期">
            </el-date-picker>
          </div>
        </div>
        <div style="display: flex; margin-top: 5px" v-if="dateType === '2'">
          <div style="display: flex; flex: 1; align-items: center; justify-content: flex-end">
            <span style="text-align: right"><span style="color: red">*</span>天数：</span>
            <el-input style="width: 200px" v-model="dateNumber" placeholder="请输入延期的天数"></el-input>
          </div>
          <div style="display: flex; flex: 1; align-items: center; justify-content: flex-end">
          </div>
        </div>
        <div style="display: flex; margin-top: 5px">
          <div style="display: flex; flex: 1; align-items: center; justify-content: flex-end">
            <span style="text-align: right"><span style="color: red">*</span>可用产品使用范围：</span>
            <el-select v-model="range" placeholder="请选择可用产品使用范围" style="width: 200px">
              <el-option
                  v-for="item in rangeList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </div>
          <div style="display: flex; flex: 1; align-items: center; justify-content: flex-end">
            <span style="text-align: right"><span style="color: red">*</span>可用的平台：</span>
            <el-select v-model="platform" placeholder="请选择可用的平台" style="width: 200px">
              <el-option
                  v-for="item in platformList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
        <div style="display: flex; margin-top: 5px">
          <div style="display: flex; flex: 1; align-items: center; justify-content: flex-end">
            <span style="text-align: right">减免服务的关键字：</span>
            <el-input style="width: 200px" v-model="keyRemark" placeholder="请输入减免服务的关键字"></el-input>
          </div>
          <div style="display: flex; flex: 1; align-items: center; justify-content: flex-end">
            <span style="text-align: right"><span style="color: red">*</span>是否有效：</span>
            <el-select v-model="isEnable" placeholder="请选择是否有效" style="width: 200px">
              <el-option
                  v-for="item in isEnableList"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value">
              </el-option>
            </el-select>
          </div>
        </div>
        <div style="display: flex; margin-top: 5px">
          <div style="display: flex; flex: 1; align-items: center; justify-content: flex-end">
            <span style="text-align: right">备注：</span>
            <el-input style="width: 200px" v-model="remark" placeholder="请输入备注"></el-input>
          </div>
          <div style="display: flex; flex: 1; align-items: center; justify-content: flex-end">
          </div>
        </div>
      </div>
      <div style="display: flex; justify-content: flex-end; margin-top: 10px">
        <el-button @click="couponClose">取 消</el-button>
        <el-button type="primary" @click="saveCouponInfo">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
        title="企业信息"
        :visible.sync="companyShow"
        width="50%"
        :before-close="companyInfoClose">
      <div>
        <div style="display: flex; margin-bottom: 10px">
          <el-input style="width: 260px" prefix-icon="el-icon-search" v-model="entName" clearable
                    placeholder="请输入企业名称"></el-input>
          <el-input style="width: 260px; margin-left: 10px" prefix-icon="el-icon-search" v-model="entTaxId" clearable
                    placeholder="请输入企业税号"></el-input>
          <el-button style="margin-left: 10px" type="primary" v-on:click="getSearchCompany">搜索</el-button>
        </div>
        <el-table
            :data="companyList"
            border
            height="400"
            style="width: 100%"
            @selection-change="selectChange">
          <el-table-column
              type="selection"
              width="55">
          </el-table-column>
          <el-table-column
              prop="entName"
              label="企业名称"
              width="230">
          </el-table-column>
          <el-table-column
              prop="entTaxId"
              label="企业税号"
              width="180">
          </el-table-column>
          <el-table-column
              prop="entType"
              label="企业类型"
              width="120"
              :formatter="getCompanyType">
          </el-table-column>
          <el-table-column
              prop="serviceStatus"
              label="企业服务状态"
              width="120"
              :formatter="getCompanyStatus">
          </el-table-column>
        </el-table>
      </div>
      <div style="display: flex; justify-content: flex-end; margin-top: 10px">
        <el-pagination
            @size-change="getCompanyNumberPage"
            @current-change="getCompanyPageNumber"
            :current-page.sync="companyPageNumber"
            :page-sizes="[10, 30, 50, 100, 300, 500]"
            :page-size="companyNumberPage"
            layout="total, sizes, prev, pager, next"
            :total="companyTotalPage">
        </el-pagination>
      </div>
      <div style="display: flex; justify-content: flex-end; margin-top: 10px">
        <el-button @click="companyInfoClose">取 消</el-button>
        <el-button type="primary" @click="batchPushCoupon">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
        title="企业信息"
        :visible.sync="isShowExportPage"
        width="50%"
        :before-close="exportPageClose">
      <div>
        <el-table
            :data="selectEnts"
            border
            height="400"
            style="width: 100%">
          <el-table-column
              prop="entName"
              label="企业名称"
              width="230">
          </el-table-column>
          <el-table-column
              prop="entTaxId"
              label="企业税号"
              width="180">
          </el-table-column>
        </el-table>
      </div>
      <div style="display: flex; justify-content: flex-end; margin-top: 10px">
        <el-button @click="exportPageClose">取 消</el-button>
        <el-button type="primary" @click="batchPushCoupon">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import cache from '@/utils/cache'
import { AxiosRequestData } from '@/data/axios_request'
import { GetCompanyType, GetCompanyServiceStatus } from '@/utils/enumeration'
import { get_excel_data } from '@/utils/Export2Excel'

export default {
  name: 'coupon_manage',
  data() {
    return {
      token: '',
      couponList: [],
      ispId: '',
      entName: '',
      entTaxId: '',
      tableHeight: '',
      totalPage: 0,
      numberPage: 10,
      pageNumber: 1,
      pageNum: 1,
      pageSize: 10,
      companyPageNumber: 1,
      companyPageSize: 10,
      companyNumberPage: 10,
      companyTotalPage: 0,
      isShow: false,
      title: '',
      amount: '',
      meetAmount: '',
      dateType: '1',
      beginDate: null,
      endDate: null,
      dateNumber: '',
      dateTypeList: [
        {
          value: '1',
          label: '固定日期'
        },
        {
          value: '2',
          label: '相对日期'
        }
      ],
      couponType: '1',
      couponTypeList: [
        {
          value: '1',
          label: '满减'
        },
        {
          value: '2',
          label: '立减'
        }
      ],
      range: '0',
      rangeList: [
        {
          value: '0',
          label: '所有的产品'
        }
      ],
      platform: '0',
      platformList: [
        {
          value: '0',
          label: '所有的平台渠道'
        }
      ],
      isEnable: false,
      isEnableList: [
        {
          value: true,
          label: '是'
        },
        {
          value: false,
          label: '否'
        }
      ],
      keyRemark: '',
      remark: '',
      isEdit: false,
      taxName: '',
      taxId: '',
      device: '',
      transactionStatusList: [
        {
          value: '',
          label: '全部'
        },
        {
          value: 1,
          label: '未付款'
        },
        {
          value: 2,
          label: '已付款'
        }
      ],
      transactionStatus: '',
      invoiceStatus: '',
      account: '',
      companyShow: false,
      companyList: [],
      selectCompanyList: [],
      entTaxIdList: [],
      couponId: '',
      couponTitle: '',
      selectEnts: [], // 选择企业
      tableHeader: [],
      tableBody: [],
      isShowExportPage: false,
      loading: false,
      loadingText: '文件导入中，请稍等！'
    }
  },
  created() {
    this.tableHeight = window.innerHeight - 250
    let company = JSON.parse(cache.getLocal('ISP'))
    let user = JSON.parse(cache.getLocal('user'))
    this.ispId = company.ispId
    this.token = cache.getToken()
    this.account = user.account
    this.getCoupon()
  },
  mounted() {
    this.tableHeight = window.innerHeight - 250
    window.onresize = () => {
      return (() => {
        this.tableHeight = window.innerHeight - 250
      })()
    }
  },
  methods: {
    // 查询优惠券信息
    getSearchCoupon() {
      this.pageNumber = 1
      this.numberPage = 10
      this.getCoupon()
    },
    // 获取优惠券信息
    getCoupon: async function () {
      if (this.token) {
        const url = '/marketing/coupon/findPage'
        let response = await AxiosRequestData(
            url,
            this.token,
            {
              title: this.couponTitle,
              ispId: this.ispId,
              pageNum: this.pageNumber,
              pageSize: this.numberPage
            },
            false,
            2
        )
        if (response) {
          if (response.code === 0) {
            this.couponList = response.data.records
            this.totalPage = response.data.total
          }
        }
      }
    },
    // 获取当前页码
    getPageNumber(num) {
      this.pageNumber = num
      this.getCoupon()
    },
    // 获取每页显示数据的数量
    getNumberPage(numPage) {
      this.numberPage = numPage
      this.getCoupon()
    },
    // 显示新增优惠券信息页面
    couponShow() {
      this.isShow = true
    },
    // 保存优惠券信息
    async saveCouponInfo() {
      if (!this.title) {
        this.$message({
          message: '优惠券标题不能为空！',
          type: 'warning'
        })
        return
      }
      if (!this.amount) {
        this.$message({
          message: '优惠的金额不能为空！',
          type: 'warning'
        })
        return
      }
      if (!this.meetAmount) {
        this.$message({
          message: '需要满足的金额不能为空！',
          type: 'warning'
        })
        return
      }
      if (this.dateType === '1') {
        if (!this.beginDate) {
          this.$message({
            message: '开始日期不能为空！',
            type: 'warning'
          })
          return
        }
        if (!this.endDate) {
          this.$message({
            message: '结束日期不能为空！',
            type: 'warning'
          })
          return
        }
      } else {
        if (!this.dateNumber) {
          this.$message({
            message: '天数不能为空！',
            type: 'warning'
          })
          return
        }
      }
      if (this.token) {
        const url = '/marketing/coupon/save'
        let response = await AxiosRequestData(
            url,
            this.token,
            {
              title: this.title,
              type: this.couponType,
              amount: this.amount,
              meetAmount: this.meetAmount,
              expiryType: this.dateType,
              beginDate: this.beginDate,
              endDate: this.endDate,
              delayDays: this.dateNumber,
              availableProduct: this.range,
              availableChannel: this.platform,
              remark: this.remark,
              keyWord: this.keyRemark,
              ispId: this.ispId,
              enable: this.isEnable,
              mobile: this.account,
              reqChannel: 4
            },
            false,
            1
        )
        if (response) {
          if (response.code === 0) {
            this.isShow = false
            this.$message({
              message: '保存成功！',
              type: 'success'
            })
            await this.getCoupon()
            this.couponClose()
          } else {
            this.$message.error(response.msg)
          }
        }
      }
    },
    // 企业信息页面关闭
    couponClose() {
      this.isShow = false
      this.title = ''
      this.amount = ''
      this.meetAmount = ''
      this.dateType = '1'
      this.beginDate = null
      this.endDate = null
      this.dateNumber = ''
      this.couponType = '1'
      this.range = '0'
      this.platform = '0'
      this.remark = ''
      this.keyRemark = ''
    },
    // 获取优惠券类型名称
    getCouponType(row, column, cellValue) {
      let result = cellValue
      if (cellValue === '1') {
        result = '满减'
      } else if (cellValue === '2') {
        result = '立减'
      }
      return result
    },
    // 获取可用范围信息
    getRangeType(row, column, cellValue) {
      let result = cellValue
      if (cellValue === '0') {
        result = '所有的产品'
      }
      return result
    },
    // 获取可用平台信息
    getPlatformType(row, column, cellValue) {
      let result = cellValue
      if (cellValue === 0) {
        result = '所有的平台渠道'
      }
      return result
    },
    // 获取有效期类型名称
    getDateType(row, column, cellValue) {
      let result = cellValue
      if (cellValue === '1') {
        result = '固定日期'
      } else if (cellValue === '2') {
        result = '相对日期'
      }
      return result
    },
    // 有效期类型变化事件
    dateTypeChange() {
      if (this.dateType === '1') {
        this.dateNumber = ''
      } else {
        this.beginDate = null
        this.endDate = null
      }
    },
    // 可用状态变化处理
    async statusChange(id, status) {
      if (this.token) {
        const url = '/marketing/coupon/changeEnable'
        let response = await AxiosRequestData(
            url,
            this.token,
            {
              couponId: id,
              enable: status,
              ispId: this.ispId,
              mobile: this.account,
              reqChannel: 4
            },
            false,
            1
        )
        if (response) {
          if (response.code === 0) {
            this.isShow = false
            this.$message({
              message: '保存成功！',
              type: 'success'
            })
            await this.getCoupon()
          } else {
            this.$message.error(response.msg)
          }
        }
      }
    },
    // 显示企业信息页面
    getCompanyShow(row) {
      this.couponId = row.couponId
      this.companyShow = true
      this.getCompanyInfo()
    },
    // 获取企业信息
    async getCompanyInfo() {
      if (this.token) {
        const url = '/sys/entInfo/findPageByMobile'
        let response = await AxiosRequestData(
            url,
            this.token,
            {
              entTaxId: this.entTaxId,
              entName: this.entName,
              userMobile: this.account,
              pageNum: this.companyPageNumber,
              pageSize: this.companyNumberPage,
              reqChannel: 4
            },
            false,
            2
        )
        if (response) {
          if (response.code === 0) {
            this.companyList = response.data.records
            this.companyTotalPage = response.data.total
          } else {
            this.$message.error(response.msg)
          }
        }
      }
    },
    // 获取企业信息当前页码
    getCompanyPageNumber(num) {
      this.companyPageNumber = num
      this.getCompanyInfo()
    },
    // 获取企业信息每页显示数据的数量
    getCompanyNumberPage(numPage) {
      this.companyNumberPage = numPage
      this.getCompanyInfo()
    },
    // 查询企业信息
    getSearchCompany() {
      this.companyPageNumber = 1
      this.companyNumberPage = 10
      this.getCompanyInfo()
    },
    // 企业信息页面关闭
    companyInfoClose() {
      this.companyShow = false
      this.entName = ''
      this.entTaxId = ''
      this.couponId = ''
      this.entTaxIdList = []
      this.companyPageNumber = 1
      this.companyNumberPage = 10
    },
    // 获取企业类型状态
    getCompanyType(row, column, cellValue) {
      return GetCompanyType(row, column, cellValue)
    },
    // 获取企业服务类型状态
    getCompanyStatus(row, column, cellValue) {
      return GetCompanyServiceStatus(row, column, cellValue)
    },
    // 企业信息选择触发事件
    selectChange(list) {
      this.selectCompanyList = list
      let listInfo = []
      list.forEach((item, index) => {
        listInfo = listInfo.concat(item.entTaxId)
      })
      this.entTaxIdList = listInfo
    },
    // 批量推送优惠券
    async batchPushCoupon() {
      if (this.token) {
        const url = '/marketing/ent/coupon/batchDeliver'
        let response = await AxiosRequestData(
            url,
            this.token,
            {
              couponId: this.couponId,
              entTaxIds: this.entTaxIdList,
              ispId: this.ispId,
              mobile: this.account,
              reqChannel: 4
            },
            false,
            1
        )
        if (response) {
          if (response.code === 0) {
            this.companyShow = false
            this.isShowExportPage = false
            this.$message({
              message: '推送成功！',
              type: 'success'
            })
          } else {
            this.$message.error(response.msg)
          }
        }
      }
    },
    // 导入企业列表
    handleImportExcel(row) {
      this.couponId = row.couponId
      this.$refs['uploadExcel-input'].click()
    },
    // 读取文件内容
    handkeFileChange(ev) {
      this.loading = true
      const files = ev.target.files
      const file = files[0]
      get_excel_data(file, (data) => {
        let status = false
        this.tableHeader = data.header
        this.tableBody = data.body
        let tempList = []
        for (const item of this.tableBody) {
          if (item['企业名称'] === undefined && item['企业税号'] === undefined) {
            status = true
          }
          tempList.push({
            entName: item['企业名称'],
            entTaxId: item['企业税号']
          })
        }
        if (!status) {
          let listInfo = []
          tempList.forEach((item, index) => {
            listInfo = listInfo.concat(item.entTaxId)
          })
          this.loading = false
          this.entTaxIdList = listInfo
          this.selectEnts = tempList
          this.isShowExportPage = true
          // fix can't select same file
          this.$refs['uploadExcel-input'].value = null
        } else {
          this.loading = false
          this.$message.error('导入文件信息错误，请检查文件内容是否正确！')
          this.tableHeader = []
          this.tableBody = []
          this.$refs['uploadExcel-input'].value = null
        }
      })
    },
    // 导入企业信息页面关闭
    exportPageClose() {
      this.tableHeader = []
      this.tableBody = []
      this.entTaxIdList = []
      this.selectEnts = []
      this.isShowExportPage = false
    },
    // 下载企业列表模板文件
    handleDownloadTemplate() {
      import('@/utils/Export2Excel').then((excel) => {
        const tHeader = ['企业名称', '企业税号']
        excel.export_json_to_excel({
          header: tHeader,
          data: '',
          filename: '批量导入优惠券分发企业信息'
        })
      })
    }
  }
}
</script>

<style scoped>

</style>
