<template>
  <div class="form-wrap">
    <el-form
      class="search-box"
      ref="form"
      :model="form"
      :inline="true"
    >
      <div class="block-title">
        查询条件
      </div>
      <el-form-item
        label="时间范围"
        prop="ticketTypeName"
      >
        <el-date-picker
          v-model="form.createTime"
          style="width:240px"
          type="daterange"
          format="yyyy-MM-dd"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="场次"
        prop="curBatchConfigId"
      >
        <el-select
          v-model="curBatchConfigId"
          placeholder="请选择场次"
          style="width: 200px;"
          @change="switchBatchConfig"
        >
          <el-option
            v-for="item in batchConfigList"
            :key="item.batchConfigId"
            :label="item.batchName"
            :value="item.batchConfigId"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <div class="btn-wrap">
        <el-button
          @click="reset"
        >
          重置
        </el-button>
        <el-button
          type="primary"
          @click="getBatchList"
        >
          搜索
        </el-button>
      </div>
    </el-form>

    <div class="table-box">
      <!-- <div class="block-title">
        现有票种
      </div> -->
      <el-tag type="warning">-1表示为不限制</el-tag>
      <el-table
        border
        stripe
        v-loading="loading"
        :data="tableData"
        style="margin-bottom: 20px;"
      >
        <el-table-column
          prop="batchName"
          label="场次信息"
          width="150"
          fixed="left"
        >
          <template slot-scope="scope">
            <div>
              <span class="label" style="font-weight: bold">场次名称：</span>
              <span class="value">{{ scope.row.batchName }}</span>
            </div>
            <div>
              <span class="label" style="font-weight: bold">开始时间：</span>
              <span class="value">{{ scope.row.startTime }}</span>
            </div>
            <div>
              <span class="label" style="font-weight: bold">结束时间：</span>
              <span class="value">{{ scope.row.endTime }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          v-for="date in dateColumns"
          :key="date"
          :label="date"
          :prop="date"
          min-width="120"
        >
          <template slot-scope="scope">
            <div style="font-size: 14px" v-if="getMaxSaleNum(date, scope.row) === -1">
              <div><span style="font-weight: bold">余量：</span><span style="color: green">不限</span></div>
              <div><span style="font-weight: bold">已售：</span><span style="color: blue">{{ getDateSoledNum(date, scope.row) }}</span></div>
            </div>
            <div style="font-size: 14px" v-else>
              <div><span style="font-weight: bold">库存：</span><span style="color: blue">{{ getMaxSaleNum(date, scope.row) }}</span></div>
              <div><span style="font-weight: bold">已售：</span><span style="color: orange">{{ getDateSoledNum(date, scope.row) }}</span></div>
              <div><span style="font-weight: bold">余量：</span><span style="color: green">{{ getDateLeftNum(date, scope.row) }}</span></div>
            </div>
            <div style="display:flex; justify-content: space-between; margin-top: 5px;">
              <div>
                <i
                  class="el-icon-s-opportunity"
                  :title="getDateStatus(date, scope.row) === 1 ? '可售' : '停售'"
                  :style="{ color: getDateStatus(date, scope.row) === 1 ? 'green' : 'red', fontSize: '16px' }"></i>
                <span :style="{ color: getDateStatus(date, scope.row) === 1 ? 'green' : 'red', fontSize: '14px' }">{{ getDateStatus(date, scope.row) === 1 ? '可售' : '停售' }}</span>
              </div>
              <i
                class="el-icon-edit"
                @click="editDate(date, scope.row)"></i>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <!-- 票种弹框 -->
    <el-dialog
      title="编辑"
      :visible.sync="dateItemDialogVisible"
      width="80%"
      :close-on-click-modal="false"
      @close="dateItemDialogVisible = false">
      <el-form
        ref="dateItemForm"
        :model="dateItem"
        :rules="dateItemRules"
        label-width="120px">
        <el-form-item
          label="场次名称"
          prop="batchConfigName"
        >
          <span>{{ dateItem.batchConfigName }}</span>
        </el-form-item>
        <el-form-item
          label="场次日期"
          prop="batchConfigName"
        >
          <span>{{ dateItem.batchDate }}</span>
        </el-form-item>
        <el-form-item
          label="最大售卖数量"
          prop="maxSaleNums"
        >
          <el-input-number
            v-model="dateItem.maxSaleNums"
            placeholder="请输入"
            :min="-1"
          />
        </el-form-item>
        <el-form-item
          label="售卖状态"
          prop="status"
        >
          <el-switch
            v-model="dateItem.status"
            :active-value="1"
            :inactive-value="0"
          />
        </el-form-item>
      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button @click="dateItemDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleDateItemSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import moment from 'moment'
import { getBatchList, updateBatch } from '@/api/batch'
import { TicketCategory } from './ticket/constant'
import { cloneDeep } from '@/utils'

const getCheckTypeName = (type) => {
  switch (type) {
    case 'qrcode':
      return '二维码'
    case 'face':
      return '人脸'
    case 'card':
      return 'IC卡'
    case 'idcard':
      return '身份证'
    case 'manual_check':
      return '人工检票'
    case 'print_check':
      return '取票即检票'
    case 'buy_check':
      return '购买即检票'
    default:
      break
  }
}

const getCheckRuleName = (rule) => {
  switch (rule) {
    case '1':
      return '人工，检票设备核销'
    case '2':
      return '取票即核销'
    case '3':
      return '购买即核销'
    default:
      break
  }
}

export default {
  data () {
    return {
      form: {
        createTime: [new Date(moment().format('YYYY-MM-DD')), new Date(moment().add(7, 'days').format('YYYY-MM-DD'))], // 下单时间
        batchDateStart: moment().format('YYYY-MM-DD'),
        batchDateEnd: moment().add(7, 'days').format('YYYY-MM-DD')
      },
      loading: false,
      tableData: [],
      memberTypeList: [],
      dialogVisible: false,
      // 弹框类型 'add' 或 'edit'
      dialogType: '',
      curItem: {},
      scenicList: [],
      ticketTagList: [],
      ticketPricePlanList: [],
      InvoiceSeller: [],
      batchConfigList: [],
      curBatchConfigId: '',
      dateItemDialogVisible: false,
      dateItem: {
        batchConfigId: '',
        batchDate: '',
        batchConfigName: '',
        status: 1,
        maxSaleNums: 0
      }
    }
  },
  computed: {
    ticketCategory () {
      return this.$store.state.app.ticketCategory
    },
    permissionList () {
      return this.$store.state.user.menuList || []
    },
    dateColumns () {
      const { batchDateStart, batchDateEnd } = this.form

      const start = moment(batchDateStart)
      const end = moment(batchDateEnd)
      const dates = []

      while (start.isSameOrBefore(end)) {
        dates.push(start.format('YYYY-MM-DD'))
        start.add(1, 'days')
      }
      return dates
    }
  },
  filters: {
    runStopColor (input) {
      return input ? 'success' : 'danger'
    },
    checkTypeFilter (input) {
      if (!input) return ''
      const types = input.split(',')
      let result = ''

      types.forEach(type => {
        result += getCheckTypeName(type) + '、'
      })
      return result.slice(0, -1) // 去掉最后一个逗号
    },
    checkRuleFilter (input) {
      if (!input) return ''
      const rules = input.split(',')
      let result = ''

      rules.forEach(rule => {
        result += getCheckRuleName(rule) + '、'
      })
      return result.slice(0, -1) // 去掉最后一个逗号
    }
  },
  created () {
    this.getBatchList()
  },
  methods: {
    getScenicName (scenicList) {
      if (!scenicList || scenicList.length === 0) return ''
      return scenicList.map(s => s.scenicName).join('、')
    },
    getTicketCate (cate) {
      return TicketCategory[cate]
    },
    showDialog (type, item) {
      if (type === 'priceCalendar') {
        this.$refs.priceCalendarRef.show(item)
        return
      }
      this.dialogType = type
      this.curItem = item
      this.$refs.ticketDialogRef.show(item, type)
      this.dialogVisible = true
    },
    hasPermission (key) {
      return !!this.permissionList.some(item => item.code === key)
    },
    editDate (date, item) {
      this.dateItem = {
        batchConfigId: item.batchConfigId,
        batchDate: date,
        batchConfigName: item.batchName,
        status: this.getDateStatus(date, item),
        maxSaleNums: this.getMaxSaleNum(date, item)
      }
      this.dateItemDialogVisible = true
    },
    handleDateItemSubmit () {
      updateBatch({
        batchConfigId: this.dateItem.batchConfigId,
        batchDate: this.dateItem.batchDate,
        status: this.dateItem.status,
        maxSaleNums: this.dateItem.maxSaleNums
      }).then((res) => {
        if (res.code === '200') {
          this.$message.success('保存成功')
          this.getBatchList()
          this.dateItemDialogVisible = false
        } else {
          this.$message.error(res.msg || '保存失败')
        }
      })
    },
    getDateLeftNum (date, item) {
      const dateObj = item.batchResponseList.find(d => d.batchDate === date)
      if (dateObj) {
        return dateObj.leftNums
      }
      return '-'
    },
    getDateTotalNum (date, item) {
      const dateObj = item.batchResponseList.find(d => d.batchDate === date)
      if (dateObj) {
        return dateObj.maxSaleNums
      }
      return '-'
    },
    getDateSoledNum (date, item) {
      const dateObj = item.batchResponseList.find(d => d.batchDate === date)
      if (dateObj) {
        return dateObj.soledNums
      }
      return '-'
    },
    getMaxSaleNum (date, item) {
      const dateObj = item.batchResponseList.find(d => d.batchDate === date)
      if (dateObj) {
        return dateObj.maxSaleNums
      }
      return '-'
    },
    getDateStatus (date, item) {
      const dateObj = item.batchResponseList.find(d => d.batchDate === date)
      if (dateObj) {
        return dateObj.status
      }
      return 0
    },
    // '创建票种失败，名称或助记符重复' 复制时去掉名称和助记符，待复制时用户填入
    itemWithoutCategoryAndShorthand (item) {
      const copyItem = cloneDeep(item)
      copyItem.name = '' // 名称
      copyItem.id = ''
      return copyItem
    },
    switchBatchConfig (value) {
      const selectedBatch = this.batchConfigList.find(batch => batch.batchConfigId === value)

      if (selectedBatch) {
        this.tableData = [selectedBatch]
      }
    },
    getBatchList () {
      this.loading = true
      this.form.batchDateStart = moment(this.form.createTime[0]).format('YYYY-MM-DD')
      this.form.batchDateEnd = moment(this.form.createTime[1]).format('YYYY-MM-DD')
      getBatchList(this.form).then(res => {
        this.batchConfigList = res.data || []
        this.tableData = this.batchConfigList
        this.loading = false
      })
    },
    handleSizeChange (size) {
      this.form.pageSize = size
      this.getBatchList()
    },
    // 获取票种列表
    handleClose () {
      this.dialogVisible = false
    }
  }
}
</script>

<style lang="scss" scoped>
.offSale-btn{
  color: #F56C6C
}
.onSale-btn{
  color: #67C23A
}
</style>
