<template>
  <a-modal
    title='操作'
    style='top: 20px;'
    :width='1000'
    v-model='visible'
    :confirmLoading='confirmLoading'
    @ok='handleSubmit'
  >
    <a-form :form='form'>
      <a-form-item style='display:none'>
        <a-input v-decorator="['id']" />
      </a-form-item>
      <a-form-item style='display:none'>
        <a-input v-decorator="['version']" />
      </a-form-item>

      <div style='display: flex;margin-bottom: 20px'>
        <span style='width: 20px;display: block;font-size: 25px;color: #1890ff;font-weight: bold;'>|</span>
        <span style='display: block;margin-top: 11px;font-size: 15px'>新增优惠券</span>
      </div>

      <a-row>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属地区'>
            <a-select v-decorator="['tenantId', {rules: [{ required: true, message: '请选择所属地区' }]}]"
                      @change='selectTenant'
                      :disabled='tenantEnable'>
              <a-select-option v-for='item in tenantList' :key='item.id'>{{ item.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='所属园区'>
            <a-select v-decorator="['parkId', {rules: [{ required: true, message: '请选择所属园区' }]}]"
                      @change='selectPark'
                      :disabled='parkEnable'>
              <a-select-option v-for='item in parkList' :key='item.id'>{{ item.name }}</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='优惠券名称'>
            <a-input placeholder='优惠券名称'
                     v-decorator="['title',{rules: [{ required: true, message: '优惠券名称'}]}]" />
          </a-form-item>
        </a-col>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='优惠券类型'>
            <a-select
              placeholder='请选择类型' v-decorator="['type',{rules: [{ required: true, message: '优惠券类型'}]}]"
              @change='getType'
            >
              <a-select-option :value='1'>抵用券</a-select-option>
              <a-select-option :value='2'>优惠券</a-select-option>
            </a-select>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='优惠方式'>
            <a-input placeholder='优惠方式'
                     v-decorator="['content',{rules: [{ required: true, message: '优惠方式'}]}]" />
          </a-form-item>
        </a-col>
        <a-col :span='11'>
          <a-form-item v-if='mdl.type === 1 ' :labelCol='labelCol' :wrapperCol='wrapperCol' label='时长'>
            <a-input placeholder='时长' v-decorator="['duration',{rules: [{ required: true, message: '时长'}]}]" />
          </a-form-item>
          <a-form-item v-if='mdl.type === 2 ' :labelCol='labelCol' :wrapperCol='wrapperCol' label='折扣'>
            <a-input placeholder='折扣' v-decorator="['discount',{rules: [{ required: true, message: '折扣'}]}]" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='开始时间'>
            <a-date-picker @change='onChange'
                           v-decorator="['startTime',{rules: [{ required: true, message: '开始时间'}]}]"
                           placeholder='开始时间' />
          </a-form-item>
        </a-col>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='结束日期'>
            <a-date-picker @change='onChange'
                           v-decorator="['endDate',{rules: [{ required: true, message: '结束日期'}]}]"
                           placeholder='结束日期' />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :span='11'>
          <a-form-item :labelCol='labelCol' :wrapperCol='wrapperCol' label='发送数量' style='margin-top: 20px;'>
            <a-radio-group v-model='value' @change='onNumChange'>
              <a-radio :value='1'>
                无限制
              </a-radio>
              <a-radio :value='2'>
                有限制
              </a-radio>
              <div>
                <a-input-number v-if='value === 2' placeholder='发送数量' @change='clickNumber'
                                v-model='publicSendNum'
                                style='margin-top: 20px;width: 200px' />
              </div>
            </a-radio-group>
          </a-form-item>
        </a-col>
      </a-row>

      <div style='display: flex;margin-bottom: 20px'>
        <span style='width: 20px;display: block;font-size: 25px;color: #1890ff;font-weight: bold;'>|</span>
        <span style='display: block;margin-top: 11px;font-size: 15px'>使用企业</span>
      </div>
      <div style='display: flex;justify-content: space-between;align-items: center;margin-bottom: 20px'>
        <div style='margin-left: 50px'>
          <a @click='getCustomer'>选择企业</a>
        </div>
        <a-form layout='inline'>
          <a-form-item label='关键词' style='margin-right: 135px'>
            <a-input placeholder='请输入关键词' v-model='queryParam.title' />
          </a-form-item>
        </a-form>
      </div>

      <a-table :columns='columns'
               size='default'
               ref='table'
               style='width: 100%; padding: 0 20px;'
               :data-source='selectEnterpriseDataList'
               rowKey='id'>

        <!--               :rowSelection='{selectedRowKeys: selectEnterpriseIdList, onChange: onSelectChange}'-->
        <!--      >-->
        <a slot='name' slot-scope='text'>{{ text }}</a>
        <span slot='action' slot-scope='text, record'>
        <a @click='deleteRecord(record)'>删除</a>
        <a-divider type='vertical' />
        <a v-if='value === 2' @click='couponTicket(record)'>多发优惠劵</a>
      </span>
      </a-table>
    </a-form>

    <a-modal v-model='customerVisible' title='选择企业' width='800px' @ok='customerHandleOk()'>
      <div class='table-page-search-wrapper'>
        <a-form layout='inline'>
          <a-form-item label='关键词' style='width: 300px'>
            <a-input placeholder='请输入关键词' v-model='customerQueryParam.itemName' />
          </a-form-item>
        </a-form>
      </div>
      <div class='table-operator'>
      </div>
      <a-table
        size='default'
        ref='table'
        rowKey='id'
        :rowSelection='{ selectedRowKeys: notSelectEnterpriseIdList, onChange: onCustomerSelectChange }'
        :columns='customerColumns'
        :data-source='notSelectEnterpriseDataList'
      >
      </a-table>
    </a-modal>
    <a-modal
      title='发放优惠券'
      style='top: 20px;'
      :width='500'
      v-model='numVisible'
      :confirmLoading='confirmLoading'
      @ok='handleNumSubmit'
    >
      <a-form layout='inline'>
        <a-form-item label='发放数量'>
          <a-input-number placeholder='请输入发放数量' v-model='ticketNum' style='width: 200px' />
        </a-form-item>
      </a-form>
    </a-modal>

  </a-modal>


</template>
<script>
import { saveTicket, getTicketByCompany, get } from '@/api/admin/meeting/ticket'
import pick from 'lodash.pick'
import { STable } from '@/components'
import { getInfo } from '@/api/login'
import { getTenantList } from '@/api/tenant'
import { getParkList } from '@/api/admin/park'
import { selectCustomer } from '@/api/admin/meeting/visitorPerson'

export default {
  name: 'TicketModal',
  props: {},
  components: {
    STable
  },
  data() {
    return {
      visible: false,
      customerVisible: false,
      customerQueryParam: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      ticketId: null,
      ticketNum: 0,
      selectEnterpriseIdList: [],
      selectedRows: [],
      notSelectEnterpriseIdList: [],
      selectedCustomerRows: [],
      columns: [
        {
          title: '企业名称',
          dataIndex: 'name'
        },
        {
          title: '企业负责人',
          dataIndex: 'contacts',
          key: 'age'
        },
        {
          title: '联系电话',
          dataIndex: 'phone'
        },
        {
          title: '优惠劵总数量',
          dataIndex: 'sumNum'
        },
        // {
        //   title: '优惠劵多发数量',
        //   dataIndex: 'moreNum'
        // },
        {
          title: '操作',
          dataIndex: 'action',
          scopedSlots: { customRender: 'action' }
        }
      ],
      customerColumns: [
        {
          title: '企业名称',
          dataIndex: 'name'
        },
        {
          title: '企业负责人',
          dataIndex: 'contacts'
        },
        {
          title: '联系电话',
          dataIndex: 'phone'
        }
      ],
      CompanyList: [],
      notSelectEnterpriseDataList: [],
      selectEnterpriseDataList: [],
      // loadData: parameter => {
      //   return getTicketByCompany(Object.assign(parameter, this.queryParam))
      // },
      value: 1,
      numVisible: false,
      confirmLoading: false,
      mdl: {},
      queryParam: {},
      form: this.$form.createForm(this),
      publicSendNum: 0,
      userDetail: {},
      tenantList: [], // 地区
      parkList: [], // 园区
      tenantEnable: false,
      parkEnable: false
    }
  },
  beforeCreate() {
  },
  created() {
  },
  methods: {
    // 获取用户详细信息
    getUserDetail() {
      getInfo().then(res => {
        console.log('getUserDetail', res)
        this.userDetail = res
        // 园区：5
        if (this.userDetail.roleIds && this.userDetail.roleIds.length > 0 && this.userDetail.roleIds[0] == 5) {
          //
          // 判断：是新增就查询园区
          let { id } = this.mdl
          if (!id) {
            // 选择地区 -> 查询园区
            this.selectTenant(this.userDetail.tenantId)
            // 选择园区 -> 查询企业
            this.selectPark(this.userDetail.parkId)
          }
          //
          // 不可编辑
          this.tenantEnable = true
          this.parkEnable = true
          // 关联地区和园区
          this.mdl.parkId = this.userDetail.parkId
          this.mdl.tenantId = this.userDetail.tenantId
          this.form.setFieldsValue({
            parkId: this.mdl.parkId,
            tenantId: this.mdl.tenantId
          })
        }
      })
    },
    // 查询地区
    getTenantData() {
      getTenantList().then(res => {
        this.tenantList = res.rows
      })
    },
    // 选择地区 -> 查询园区
    selectTenant(id) {
      console.log('selectTenant', id)
      // 清空数据
      this.mdl.parkId = null // 园区
      this.selectEnterpriseDataList = []  // 选中企业
      this.notSelectEnterpriseDataList = []  // 未选中企业
      this.notSelectEnterpriseIdList = [] // 未选中id

      this.form.setFieldsValue({
        parkId: null // 园区
      })
      // 查询园区
      getParkList({
        tenantId: id
      }).then(res => {
        this.parkList = res.rows
      })
    },
    // 选择园区 -> 查询企业
    selectPark(id) {
      // 清空数据
      this.selectEnterpriseDataList = []  // 选中企业
      this.notSelectEnterpriseDataList = []  // 未选中企业
      this.notSelectEnterpriseIdList = [] // 未选中id
      // 查询企业
      getTicketByCompany({
        parkId: id
      }).then(res => {
        console.log('getTicketByCompany', res)
        this.selectEnterpriseDataList = res.rows.map(item => {
          if (!item.moreNum) {
            item.moreNum = 0
          }
          if (!item.sumNum) {
            item.sumNum = 0
          }
          // 发送数量
          if (this.value == '1') { //无限制
            item.sumNum = 1
          } else { //有限制
            item.sumNum = this.publicSendNum
          }
          return item
        })
      })
    },
    clickNumber(value) {
      this.publicSendNum = value
      // 数值改变
      this.selectEnterpriseDataList.forEach(item => {
        if (!item.moreNum) {
          item.moreNum = 0
        }
        item.sumNum = value + item.moreNum
      })
    },
    // 多发优惠券
    couponTicket(record) {
      this.numVisible = true
      this.ticketId = record.id
      this.ticketNum = record.moreNum
    },
    // 确定多发优惠券
    handleNumSubmit() {
      this.numVisible = false
      this.selectEnterpriseDataList = this.selectEnterpriseDataList.map(item => {
        if (item.id == this.ticketId) {
          console.log('this.ticketNum ', this.ticketNum)
          console.log('this.publicSendNum ', this.publicSendNum)
          item.moreNum = this.ticketNum
          item.sumNum = item.moreNum + this.publicSendNum
        }
        return item
      })
    },
    customerHandleOk() {
      let record = this.selectedCustomerRows
      record.forEach(record => {
        this.notSelectEnterpriseDataList = this.notSelectEnterpriseDataList.filter(item => item.id != record.id)
        this.selectEnterpriseDataList.push(record)
      })
      this.customerVisible = false

    },

    deleteRecord(record) {
      this.selectEnterpriseDataList = this.selectEnterpriseDataList.filter(item => item.id != record.id)
      this.notSelectEnterpriseDataList.push(record)
    },

    onSelectChange(selectedRowKeys, selectedRows) {
      console.log(selectedRowKeys, selectedRows)
      this.selectEnterpriseIdList = selectedRowKeys
      this.selectedRows = selectedRows
    },
    onCustomerSelectChange(selectedRowKeys, selectedRows) {
      this.notSelectEnterpriseIdList = selectedRowKeys
      this.selectedCustomerRows = selectedRows
    },
    getCustomer() {
      this.customerVisible = true
    },
    onNumChange(e) {
      this.value = e.target.value
      // 发送数量
      if (this.value == '1') { // 无限制
        this.selectEnterpriseDataList = this.selectEnterpriseDataList.map(item => {
          item.moreNum = 0
          item.sumNum = 1
          return item
        })
      } else { // 有限制
        this.selectEnterpriseDataList = this.selectEnterpriseDataList.map(item => {
          item.moreNum = 0
          item.sumNum = this.publicSendNum
          return item
        })
      }
    },
    getType(value) {
      this.mdl.type = value
    },
    onChange(date, dateString) {
      this.form.startTime = dateString[0]
      this.form.endDate = dateString[1]
    },
    add() {
      this.edit({ id: 0 })
    },
    edit(record) {
      this.form.resetFields()
      this.selectEnterpriseDataList = []
      this.notSelectEnterpriseDataList = []
      this.notSelectEnterpriseIdList = []
      this.mdl = Object.assign(record)
      let copyMdl = JSON.parse(JSON.stringify(this.mdl))
      // 查询地区
      this.getTenantData()
      this.visible = true
      if (record.id > 0) {
        // 查询园区
        if(copyMdl.tenantId){
          // 选择地区 -> 查询园区
          this.mdl = JSON.parse(JSON.stringify(copyMdl))
          this.selectTenant(copyMdl.tenantId)
        }
        // 防止替换
        this.mdl = JSON.parse(JSON.stringify(copyMdl))
        //
        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.mdl, 'id', 'tenantId', 'parkId', 'title', 'content', 'duration', 'type', 'money',
            'address', 'isVerification', 'enterpriseIds', 'isShow', 'startTime', 'endDate', 'remark',
            'isDefault', 'version', 'deleteFlag', 'createBy', 'createTime', 'updateBy', 'updateTime', 'discount'))
        })
        get(record.id).then(res => {
          // 选择企业
          this.selectEnterpriseDataList = res.selectCustomerList
          // this.selectEnterpriseIdList = res.selectCustomerList.map(item => item.id)
          // 未选中企业
          this.notSelectEnterpriseDataList = res.notSelectCustomerList
          // this.notSelectEnterpriseIdList = res.notSelectCustomerList.map(item => item.id)

          //获取发送数量限制字段
          this.value = res.isVerification

          if (res.num) { // 有限制
            this.publicSendNum = res.num
            this.notSelectEnterpriseDataList.map(item => item.sumNum = res.num)
          } else { // 无限制
          }
        })

      } else {

      }
      // 获取用户详细信息
      this.getUserDetail()
    },
    handleSubmit(e) {
      e.preventDefault()
      this.form.validateFields((err, values) => {
        if (!err) {
          // 选择企业
          values.ticketCustomerVo = this.selectEnterpriseDataList
          values.num = this.publicSendNum
          values.isVerification =this.value
          this.confirmLoading = true
          saveTicket(values).then(res => {
            if (res.code === 0) {
              this.$message.success('保存成功')
              this.$emit('ok')
              this.visible = false
            } else {
              this.$message.error(res.msg)
            }
          }).catch(() => {
            this.$message.error('系统错误，请稍后再试')
          }).finally(() => {
            this.confirmLoading = false
          })
        }
      })
    }
  },
  watch: {}
}
</script>
