<template>
  <el-dialog
    append-to-body
    title="设置退款金额"
    :visible.sync="visible"
    width="700px"
    @close="handleClose">
    <el-form
      :model="form"
      ref="form"
      label-width="80px"
      style="padding:20px">
      <el-form-item
        verify
        label="退款金额">
        <el-input-number
          v-model="form.refund_price"
          :precision="2"
          :step="0.01"
          :min="0.01"></el-input-number>
      </el-form-item>
    </el-form>
    <button
      @click="fooBarHandler"
      v-if="false">
      测试
    </button>
    <div class="block-title">
      可退景点列表
    </div>
    <el-table
      border
      stripe
      ref="scenicMoneyTable"
      v-if="data && data.ticketScenic && data.ticketScenic.length"
      :data="data.ticketScenic"
      :row-key="(row) => { return row.id }"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        reserve-selection
        :selectable="setSelectable"
        width="55">
      </el-table-column>
      <el-table-column
        width="160"
        prop="id"
        label="票景点id"
      >
      </el-table-column>
      <el-table-column
        width="160"
        prop="scenic_name"
        label="景点名"
      >
      </el-table-column>
      <el-table-column
        width="160"
        prop="checked_times"
        label="是否是可退的未检票"
      >
        <template slot-scope="scope">
          {{ scope.row.checked_times === 0 ? '是' : '否' }}
        </template>
      </el-table-column>
      <el-table-column
        width="160"
        prop="partPrice"
        label="景点部分价格"
      >
        <template slot-scope="scope">
          {{ scope.row.partPrice + ' 元' }}
        </template>
      </el-table-column>
    </el-table>

    <div
      class="block-title"
      style="margin-top: 20px;">
      退款原因（单选必填）
    </div>

    <!-- <el-radio
      :label="1">
      扫码开票
    </el-radio> -->

    <el-radio-group
      v-model="selectedReason"
      @change="handleRadioChange"
      style="padding-left: 30px;">
      <el-radio
        style="display: block;margin-bottom: 10px;"
        v-for="(reason, index) in ReasonList"
        :key="index"
        :label="reason">
        {{ reason }}
      </el-radio>
    </el-radio-group>

    <div
      v-show="['自定义原因', '其他原因'].includes(selectedReason)"
      class="block-title"
      style="margin-top: 20px;">
      部分退款原因补充说明
    </div>

    <el-input
      v-show="['自定义原因', '其他原因'].includes(selectedReason)"
      type="textarea"
      :rows="4"
      placeholder="请输入部分退款原因"
      style="padding:20px;width: 600px;"
      v-model="form.cancel_remark">
    </el-input>

    <span slot="footer">
      <el-button @click="visible = false">取 消</el-button>
      <el-button
        type="primary"
        :loading="loading"
        @click="submitWrapper">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { cancelPartTicket } from '@/api/order'
import { getSystemConfigList } from '@/api/systemConfig'
export default {
  computed: {
    salesList () {
      return this.$store.state.user.salesList
    }
  },
  data () {
    return {
      visible: false,
      loading: false,
      data: {},
      selectedReason: '', // 与form.cancel_remark同步
      form: {
        refund_price: 0.01,
        id: '',
        cancel_remark: ''
      },
      ReasonList: [],
      mockReasons: [
        '天气原因不方便出行',
        '换票不方便',
        '未带入园证件',
        '计划有变不想去了',
        '其他原因'
      ]
    }
  },
  methods: {
    fooBarHandler () {
      console.log('data', this.data)
      console.log('ticketScenic', this.data.ticketScenic)
    },
    handleRadioChange (val) {
      if (!['自定义原因', '其他原因'].includes(val)) {
        this.form.cancel_remark = val
      } else {
        this.form.cancel_remark = ''
      }
    },
    handleSelectionChange (val) {
      console.log('选中景点票', val)
      console.log('选中可退金额', val.filter(item => item.checked_times === 0)
        .reduce((acc, item) => acc + item.partPrice, 0))
      this.selectedValArr = val
      if (val && val.length) {
        this.selectedReturnMoney = val.reduce((acc, item) => acc + item.partPrice, 0)
      } else {
        this.selectedReturnMoney = 0
      }
      this.form.refund_price = this.selectedReturnMoney
    },
    setSelectable (row, index) {
      // 只有未检票才可部分退款
      return row.checked_times === 0
    },
    show (data) {
      this.visible = true
      this.data = data
      this.form.id = data.id
      // 清空选中的原因
      this.form.cancel_remark = ''
      this.selectedReason = ''
      // 确保组件加载完毕
      this.$nextTick(() => {
        this.$refs.scenicMoneyTable.clearSelection() // 先清空选择
        this.$refs.scenicMoneyTable.toggleAllSelection() // 翻转全选状态
      })
      // 获取系统配置里的原因
      getSystemConfigList().then(res => {
        let configArr = res.list.filter(item => item.configKey === 'ticket_cancel_reason')
        if (!configArr.length) {
          this.ReasonList = this.mockReasons
        } else {
          let reasonsStr = configArr[0].configValue
          console.log('获取到逗号分隔的退款原因字符串', reasonsStr)
          console.log('获取到逗号分隔的退款原因列表', reasonsStr.split('|'))
          this.ReasonList = reasonsStr.split('|')
        }
      })
    },
    handleClose () {
      this.visible = false
    },
    submitWrapper () {
      // 必须得选个原因
      if (!this.selectedReason.length) {
        this.$message.error('请选择退款原因')
        return
      }
      if (!this.form.cancel_remark.length) {
        this.$message.error('请输入部分退款原因补充说明')
        return
      }
      this.submit()
    },
    submit () {
      if (this.form.refund_price > this.data.price) {
        this.$message.error('退款金额不得大于票价')
        return false
      }
      this.$confirm('确认退款', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        this.$refs.form.validate(valid => {
          if (valid) {
            let list = []
            list.push(this.form)
            cancelPartTicket({ list }).then(res => {
              this.$message.success('退款成功')
            }).finally(() => {
              this.$emit('change')
              this.loading = false
            })
          }
        })
        this.handleClose()
      })
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-dialog .el-form-item {
  display: inline-block;
}
::v-deep .el-form-item__content{
    width: 200px;
}
</style>
