<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-input v-model="form.ticketTypeName"></el-input>
      </el-form-item>
      <el-form-item
        label="类型"
        prop="category"
      >
        <el-select v-model="form.category">
          <el-option
            value=""
            label="全部"
          ></el-option>
          <el-option
            v-for="item in ticketCategory"
            :key="item.id"
            :value="item.id"
            :label="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="是否可售"
        prop="isSale"
      >
        <el-select v-model="form.isSale">
          <el-option
            label="全部"
            value=""
          ></el-option>
          <el-option
            label="是"
            :value="1"
          ></el-option>
          <el-option
            label="否"
            :value="0"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="景点"
        prop="scenicId"
      >
        <el-select v-model="form.scenicId">
          <el-option
            value=""
            label="全部"
          ></el-option>
          <el-option
            v-for="item in scenicList"
            :key="item.id"
            :value="item.id"
            :label="item.name">
          </el-option>
        </el-select>
      </el-form-item>
      <div class="btn-wrap">
        <el-button
          @click="reset"
        >
          重置
        </el-button>
        <el-button
          type="primary"
          @click="getTicketTypeList"
        >
          搜索
        </el-button>

        <el-button
          type="primary"
          @click="showDialog('add')"
        >
          新增票种
        </el-button>
      </div>
    </el-form>

    <div class="table-box">
      <!-- <div class="block-title">
        现有票种
      </div> -->
      <el-table
        border
        stripe
        v-loading="loading"
        :data="tableData"
      >
        <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-switch
              @change="handelStatusChange($event,scope.row)"
              v-model="scope.row.isSale"
              active-text="在售"
              inactive-text="禁售"
              :active-value="1"
              :inactive-value="0">
            </el-switch>
          </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-column
          label="团散"
        >
          <template slot-scope="scope">
            {{ scope.row.teamIndividual === 1 ? '散客' : scope.row.teamIndividual === 2 ? '团队' : '不限' }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
        >
          <template slot-scope="scope">
            <el-link
              type="primary"
              size="small"
              @click="showDialog('edit', scope.row)"
            >
              编辑
            </el-link>
            <el-link
              type="primary"
              size="small"
              @click="showDialog('priceCalendar', scope.row)"
            >
              价格日历
            </el-link>
            <br>
            <el-link
              type="primary"
              size="small"
              @click="showDialog('add', itemWithoutCategoryAndShorthand(scope.row))"
            >
              复制
            </el-link>
            <el-link
              type="primary"
              size="small"
              @click="deleteTicket(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="getTicketTypeList()"
        :total="total">
      </el-pagination>
    </div>
    <!-- 票种弹框 -->
    <TicketDialog
      ref="ticketDialogRef"
      :dialog-type="dialogType"
      :ticket-item="curItem"
      :scenic-list="scenicList"
      :ticket-tag-list="ticketTagList"
      :member-type-list="memberTypeList"
      :invoice-seller="InvoiceSeller"
      @updateList="getTicketTypeList"
    ></TicketDialog>
    <PriceCalendar ref="priceCalendarRef"></PriceCalendar>
  </div>
</template>

<script>
import moment from 'moment'
import { getTicketTypeList, deleteTicket, getScenic, updateTicket, listInvoiceSales } from '@/api/ticketType'
import { getTicketTypeTagList } from '@/api/ticketTypeTag'
import { getMemberType } from '@/api/member'
import TicketDialog from './ticket/Dialog'
import PriceCalendar from './ticket/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: {
    ticketCategory () {
      return this.$store.state.app.ticketCategory
    }
  },
  data () {
    return {
      form: {
        ticketTypeName: '',
        scenicId: '',
        category: '',
        isSale: '',
        pageNum: 1,
        pageSize: 10
      },
      loading: false,
      total: 0,
      tableData: [],
      memberTypeList: [],
      dialogVisible: false,
      // 弹框类型 'add' 或 'edit'
      dialogType: '',
      curItem: {},
      scenicList: [],
      ticketTagList: [],
      ticketPricePlanList: [],
      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) // 去掉最后一个逗号
    }
  },
  created () {
    this.getScenicList()
    this.getTicketTypeList()
    // this.getMemberList()
    // this.getTicketTagList()
    // this.getTicketPricePlanList()
    // this.getInvoiceSeller()
  },
  components: {
    TicketDialog,
    PriceCalendar
  },
  methods: {
    getScenicName (scenicList) {
      if (!scenicList || scenicList.length === 0) return ''
      return scenicList.map(s => s.scenicName).join('、')
    },
    getTicketCate (cate) {
      return TicketCategory[cate]
    },
    getInvoiceSeller () {
      listInvoiceSales({}).then(res => {
        this.InvoiceSeller = res?.data
      })
    },
    getTicketTagList () {
      getTicketTypeTagList({}).then(res => {
        this.ticketTagList = res.children
      })
    },
    // 获取景点列表
    async getScenicList () {
      const res = await getScenic()
      this.scenicList = res?.data.records || []
    },
    async 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
    },
    // '创建票种失败，名称或助记符重复' 复制时去掉名称和助记符，待复制时用户填入
    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.getTicketTypeList()
    },
    // 获取票种列表
    getTicketTypeList () {
      this.loading = true
      getTicketTypeList(this.form).then(res => {
        this.tableData = res.data.records.map(item => {
          item.scenics = item.ticketTypeScenicList?.map(s => s.scenicName).join('、')
          return item
        })
        this.total = res.data.total || 0
      }).finally(() => {
        this.loading = false
      })

      // 更新全局票种列表
      // this.$store.dispatch('getTicketTypeList')
    },
    // 删除票种
    deleteTicket (id) {
      this.$confirm('确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        deleteTicket(id).then(res => {
          this.$message.success('删除成功')
          this.getTicketTypeList()
        })
      })
    },
    reset () {
      this.$refs.form.resetFields()
    },
    offSale (data) {
      let form = Object.assign({}, data)
      form.isSale = 0
      updateTicket(form).then(res => {
        if (res.code !== '200') {
          this.$message.success(res.msg || '操作失败')
          return
        }
        this.$message.success('操作成功')
        this.getTicketTypeList()
      })
    },
    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.ticketTypeSourceList = form.source || []
        updateTicket(form).then(res => {
          if (res.code === '200') {
            this.$message.success('操作成功')
            this.getTicketTypeList()
          }
        })
      }
    },
    handleClose () {
      this.dialogVisible = false
    },
    handelStatusChange (value, ticket) {
      const currentTicket = cloneDeep(ticket)
      currentTicket.ticketTypeSourceList = ticket.ticketTypeSourceList || ticket.source || []

      if (!currentTicket.ticketTypeSourceList) {
        currentTicket.ticketTypeSourceList = []
      }

      if (!currentTicket.ticketTypeScenicList) {
        currentTicket.ticketTypeScenicList = []
      }

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

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

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

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

      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)
      }
      currentTicket.groupScenicList = gsList
      currentTicket.isSale = value

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

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