<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="name"
      >
        <el-input v-model="form.name"></el-input>
      </el-form-item>
      <div class="btn-wrap">
        <el-button
          @click="reset"
        >
          重置
        </el-button>
        <el-button
          type="primary"
          @click="getBatchConfigList"
        >
          搜索
        </el-button>

        <el-button
          type="primary"
          @click="showDialog('add')"
        >
          新增场次
        </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"
      >
        <el-table-column type="expand">
          <template slot-scope="props">
            <div class="title" style="font-weight: bold;">绑定票种</div>
            <el-table :data="props.row.ticketTypes" :max-height="200">
              <el-table-column
                prop="id"
                label="票种ID"
                width="80"
              >
              </el-table-column>
              <el-table-column
                prop="name"
                label="票种名称"
              >
              </el-table-column>
              <el-table-column
                label="票种分类"
              >
                <template slot-scope="scope">
                  {{ getTicketCate(scope.row.category) }}
                </template>
              </el-table-column>

              <el-table-column
                prop="price"
                label="窗口价格"
              >
              </el-table-column>
              <el-table-column
                label="在售状态"
              >
                <template slot-scope="scope">
                  <el-tag
                    :type="scope.row.isSale ? 'success' : 'danger'">
                    {{ scope.row.isSale ? '在售' : '停售' }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column
                prop="useDate"
                label="使用日期"
              >
                <template slot-scope="scope">
                  {{ scope.row.useDateStart }} - {{ scope.row.useDateEnd }}
                </template>
              </el-table-column>
              <el-table-column
                prop="checkType"
                label="核销凭证"
              >
                <template slot-scope="scope">
                  {{ scope.row.checkType | checkTypeFilter }}
                </template>
              </el-table-column>
              <el-table-column
                prop="checkRule"
                label="核销规则"
              >
                <template slot-scope="scope">
                  {{ scope.row.checkRule | checkRuleFilter }}
                </template>
              </el-table-column>
              <el-table-column
                prop="checkScenic"
                label="核销景点"
              >
                <template slot-scope="scope">
                  {{ getScenicName(scope.row.ticketTypeScenicList) }}
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column
          label="场次名称"
          prop="name">
        </el-table-column>
        <el-table-column
          label="开始时间"
          width="90"
          prop="startTime">
        </el-table-column>
        <el-table-column
          label="结束时间"
          width="90"
          prop="endTime">
        </el-table-column>
        <el-table-column
          label="场次策略"
          width="90"
          prop="strategy">
          <template slot-scope="scope">
            {{ scope.row.strategy | strategyFilter }}
          </template>
        </el-table-column>
        <el-table-column
          label="策略详情"
          prop="strategy">
          <template slot-scope="scope">
            <span v-if="scope.row.strategy === 'basic'"></span>
            <span v-else-if="scope.row.strategy === 'week'">
              {{ getWeekName(scope.row.strategyContent) }}
            </span>
            <span v-else>
              {{ getPeriodName(scope.row.strategyContent) }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="开场后X分钟停止售票"
          prop="saleStopMinutes">
        </el-table-column>
        <el-table-column
          label="开场前X分钟停止退票"
          prop="cancelStopBeforeStartMinutes"
          min-width="90">
        </el-table-column>
        <el-table-column
          label="开场后X分钟停止退票"
          prop="cancelStopAfterStartMinutes"
          min-width="90">
        </el-table-column>
        <el-table-column
          label="开场前X分钟允许检票入场"
          prop="preCheckMinutes"
          min-width="90">
        </el-table-column>
        <el-table-column
          label="开场后X分钟停止检票"
          prop="stopCheckMinutes"
          min-width="90">
        </el-table-column>
        <el-table-column
          label="无座位时的最大数量"
          prop="maxSaleNums"
          min-width="90">
        </el-table-column>
        <el-table-column
          width="110"
          class-name="align-item"
          label="操作">
          <template slot-scope="scope">
            <el-link
              type="primary"
              size="small"
              @click="editBatchConfig(scope.row)">
              编辑
            </el-link>
            <el-link
              type="primary"
              size="small"
              @click="deleteBatchConfig(scope.row.id)">
              删除
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :current-page.sync="form.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="form.pageSize"
        @size-change="handleSizeChange"
        layout="total, sizes, prev, pager, next, jumper"
        @current-change="getBatchConfigList()"
        :total="total">
      </el-pagination>
    </div>
    <!-- 场次弹框 -->
    <BatchDialog
      ref="batchDialogRef"
      :dialog-type="dialogType"
      :batch-item="curItem"
      :scenic-list="scenicList"
      :batch-tag-list="batchTagList"
      :member-type-list="memberTypeList"
      :invoice-seller="InvoiceSeller"
      @update-list="initData"
    ></BatchDialog>
    <PriceCalendar ref="priceCalendarRef"></PriceCalendar>
  </div>
</template>

<script>
import moment from 'moment'
import { getBatchConfigList, updateBatchConfig, deleteBatchConfig } from '@/api/batch'
import { getMemberType } from '@/api/member'
import { strategyMap } from '@/assets/staticData'
import BatchDialog from './batchConfig/Dialog'
import PriceCalendar from './batchConfig/PriceCalendar'
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 {
  computed: {
  },
  data () {
    return {
      form: {
        name: '',
        pageNum: 1,
        pageSize: 10
      },
      loading: false,
      total: 0,
      tableData: [],
      memberTypeList: [],
      dialogVisible: false,
      // 弹框类型 'add' 或 'edit'
      dialogType: '',
      curItem: {},
      scenicList: [],
      batchTagList: [],
      batchPricePlanList: [],
      InvoiceSeller: []
    }
  },
  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) // 去掉最后一个逗号
    },
    strategyFilter (input) {
      const item = strategyMap.find(s => s.value === input)
      return item ? item.label : ''
    }
  },
  created () {
    // this.getScenicList()
    this.getBatchConfigList()
    // this.getMemberList()
    // this.getTicketTagList()
    // this.getTicketPricePlanList()
    // this.getInvoiceSeller()
  },
  components: {
    BatchDialog,
    PriceCalendar
  },
  methods: {
    initData () {
      this.form.pageNum = 1
      this.getBatchConfigList()
    },
    getTicketCate (cate) {
      return TicketCategory[cate]
    },
    getScenicName (scenicList) {
      if (!scenicList || scenicList.length === 0) return ''
      return scenicList.map(s => s.scenicName).join('、')
    },
    getWeekName (sc) {
      try {
        const wks = JSON.parse(sc)
        const weekMap = {
          1: '周日',
          2: '周一',
          3: '周二',
          4: '周三',
          5: '周四',
          6: '周五',
          7: '周六'
        }
        return wks.map(w => weekMap[w]).join('、')
      } catch (error) {
        return ''
      }
    },
    getPeriodName (period) {
      try {
        const periods = JSON.parse(period)
        return periods.map(p => p.start + '-' + p.end).join(' ')
      } catch (error) {
        return ''
      }
    },
    showDialog (type, item) {
      if (type === 'priceCalendar') {
        this.$refs.priceCalendarRef.show(item)
        return
      }
      this.dialogType = type
      this.curItem = item
      this.$refs.batchDialogRef.show(item, type)
      this.dialogVisible = true
    },
    // '创建场次失败，名称或助记符重复' 复制时去掉名称和助记符，待复制时用户填入
    itemWithoutCategoryAndShorthand (item) {
      const copyItem = cloneDeep(item)
      copyItem.name = '' // 名称
      copyItem.id = ''
      return copyItem
    },
    getMemberList () {
      getMemberType({
        pageNum: 0,
        pageSize: -1
      }).then(res => {
        this.memberTypeList = res.list
      })
    },
    handleSizeChange (size) {
      this.form.pageSize = size
      this.getBatchConfigList()
    },
    // 获取场次列表
    getBatchConfigList () {
      this.loading = true
      getBatchConfigList(this.form).then(res => {
        this.tableData = res.data.records
        this.total = res.data.total || 0
      }).finally(() => {
        this.loading = false
      })

      // 更新全局场次列表
      // this.$store.dispatch('getBatchConfigList')
    },
    editBatchConfig (item) {
      this.showDialog('edit', item)
    },
    // 删除场次
    deleteBatchConfig (id) {
      this.$confirm('确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteBatchConfig({ idList: [id] }).then(res => {
          this.$message.success('删除成功')
          this.getBatchConfigList()
        })
      })
    },
    reset () {
      this.$refs.form.resetFields()
    },
    offSale (data) {
      let form = Object.assign({}, data)
      form.isSale = 0
      updateBatchConfig(form).then(res => {
        if (res.code !== '200') {
          this.$message.success(res.msg || '操作失败')
          return
        }
        this.$message.success('操作成功')
        this.getBatchConfigList()
      })
    },
    onSale (data) {
      let saleEnd = moment(data.saleDateEnd).hours(23).minutes(59).seconds(59)
      if (moment().isAfter(saleEnd)) {
        this.$alert('请修改场次可售日期', '场次已过期', {
          confirmButtonText: '知道了'
        })
      } else {
        let form = Object.assign({}, data)
        form.isSale = 1
        form.batchTypeSourceList = form.source || []
        updateBatchConfig(form).then(res => {
          if (res.code === '200') {
            this.$message.success('操作成功')
            this.getBatchConfigList()
          }
        })
      }
    },
    handleClose () {
      this.dialogVisible = false
    },
    handelStatusChange (value, batch) {
      const currentBatch = cloneDeep(batch)
      currentBatch.batchTypeSourceList = batch.batchTypeSourceList || batch.source || []

      if (!currentBatch.batchTypeSourceList) {
        currentBatch.batchTypeSourceList = []
      }

      if (!currentBatch.batchTypeScenicList) {
        currentBatch.batchTypeScenicList = []
      }

      if (!currentBatch.singleScenicList) {
        currentBatch.singleScenicList = []
      }

      if (!currentBatch.groupScenicList) {
        currentBatch.groupScenicList = []
      }

      if (!currentBatch.batchConfigList) {
        currentBatch.batchConfigList = []
      }

      let groupFlag = ''
      let groupIndex = 0
      currentBatch.batchTypeScenicList.forEach(item => {
        if (!item.groupFlag) {
          currentBatch.singleScenicList.push({
            scenicId: item.scenicId,
            checkLimitTimes: item.checkLimitTimes,
            singleDayLimitTimes: item.singleDayLimitTimes
          })
        } else {
          if (groupFlag !== item.groupFlag) {
            groupFlag = item.groupFlag
            groupIndex += 1
            currentBatch.groupScenicList.push({
              scenicId: [item.scenicId],
              checkLimitTimes: item.checkLimitTimes,
              scenicLimitTimes: item.scenicLimitTimes,
              singleDayLimitTimes: item.singleDayLimitTimes
            })
          } else {
            currentBatch.groupScenicList[groupIndex - 1].scenicId.push(item.scenicId)
          }
        }
      })
      const gsList = []
      const { groupScenicList } = currentBatch

      for (let i = 0; i < groupScenicList.length; i++) {
        const item = groupScenicList[i]
        const sList = item.scenicId.map(scenicId => {
          return {
            scenicId,
            checkLimitTimes: item.checkLimitTimes,
            singleDayLimitTimes: item.singleDayLimitTimes || -1,
            scenicLimitTimes: item.scenicLimitTimes || -1
          }
        })
        gsList.push(sList)
      }
      currentBatch.groupScenicList = gsList
      currentBatch.isSale = value

      updateBatchConfig(currentBatch).then(res => {
        if (res.code === '200') {
          this.$message.success('操作成功')
          this.getBatchConfigList()
        }
      })
    }
  }
}
</script>

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