<template>
<a-spin :spinning="this.$store.state.spinning" :delay="delayTime">
    <div class="AllowancePayment">
      <div class="searchBox">
        <div style="width: 75px">截止时间:</div>
        <a-date-picker
          :disabledDate="disabledStartDate"
          format="YYYY-MM-DD"
          v-model="startValue"
          style="120px"
          placeholder="开始日期"
          @change="onChangeStartValue"
          @openChange="handleStartOpenChange"
        />
        <div>~</div>
        <a-date-picker
          :disabledDate="disabledEndDate"
          format="YYYY-MM-DD"
          placeholder="结束日期"
          style="120px"
          @change="onChangeEndValue"
          v-model="endValue"
          :open="endOpen"
          @openChange="handleEndOpenChange"
        />
        <a-select placeholder="津贴类型" :allowClear="true" style="width: 100px;margin-left: 15px;" @change="selectHandType">
          <a-select-option value="TRAVEL">交通补助</a-select-option>
          <a-select-option value="MEAL">餐补</a-select-option>
        </a-select>
        <a-input style="width: 120px;margin-left: 15px;" placeholder="经办人"  v-model="searchSource.agentName"/>
        <!-- <a-select placeholder="经办人" :allowClear="true" style="width: 100px;margin-left: 15px;" @change="selectAgent">
          <a-select-option v-for="(item, index) in agentList" :key="index" :value="item.ddUserId">{{ item.name }}</a-select-option>
        </a-select> -->
        <a-button type="primary" @click="search()" style="margin-left: 15px;">查询</a-button>
        <a-button type="primary" @click="changeModel()" style="margin-left: 15px;"><a-icon type="pay-circle" />发放津贴</a-button>
      </div>
      <a-table :columns="columns" :dataSource="recordsList" size="default" rowKey="grantNumber" :pagination="pagination" @change="handleTableChange">
        <span slot="recipient">成员</span>
        <span slot="money" slot-scope="money">
          {{ money.toFixed(2) }}
        </span>
        <span slot="type" slot-scope="type">{{ type === 'TRAVEL' ? '交通补助' : '餐补' }}</span>
        <span slot="agentName">经办人</span>
        <span slot="endTime" slot-scope="endTime">
          {{ endTime.split(" ")[0] }}
        </span>
        <span slot="remark">备注</span>
        <span slot="couponRecordStatus" slot-scope="couponRecordStatus">
          <a-badge v-if="couponRecordStatus === MINGPAY_SUBSIDY_STATUS.WAITING_PERMIT" status="processing" text="审批中" />
          <a-badge v-else-if="couponRecordStatus === MINGPAY_SUBSIDY_STATUS.SUCCESS" status="success" text="已完成" />
          <a-badge v-else-if="couponRecordStatus === MINGPAY_SUBSIDY_STATUS.REFUSE_PERMIT" status="error" text="审批未通过" />
        </span>
        <span slot="action" slot-scope="text, record, index" class="operationTable">
          <a href="javascript:;" @click="toAllowanceDetails(record, text, index)">查看详情</a>
        </span>
      </a-table>
      <a-modal title="发放津贴"  v-model="visible" @ok="createSubsidy()">
        <a-form :form="form">
          <a-form-item
            v-bind="formItemLayout"
            label="发放类型"
            has-feedback
          >
            <a-select
              v-decorator="[
                'select',
                {rules: [{ required: true, message: ' 津贴类型' }]}
              ]"
              placeholder="请选择津贴类型"
            >
              <a-select-option value="TRAVEL">
                交通补助
              </a-select-option>
              <a-select-option value="MEAL">
                餐补
              </a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item label="发放金额" v-bind="formItemLayout" >
            <a-input
              v-decorator="['orderPrice',{rules: [{required: true, message: '充值金额不能为空'}, {validator: rechargeNum}]}]"
            />
          </a-form-item>
          <a-form-item
            v-bind="formItemLayout"
            label="截止日期"
          >
            <a-date-picker
              placeholder="请选择截止日期"
              :disabledDate="disabledDate"
              :showToday="false"
              v-decorator="['date-picker', config]"
            />
          </a-form-item>
          <a-form-item label="选择成员" v-bind="formItemLayout">
            <div class="peopleBox" @click="choosePeople()">
              {{ peopleListStr() }}
            </div>
          </a-form-item>
          <a-form-item label="备注" v-bind="formItemLayout" >
            <a-textarea v-decorator="['remark', {rules: [{ required: true, message: '备注不能为空' }]}]"/>
          </a-form-item>
        </a-form>
      </a-modal>
    </div>
  </a-spin>
</template>

<script>
import { config } from './../../../api/config.js'
import { $http } from './../../../api/axios.js'
import { MINGPAY_SUBSIDY_STATUS } from './../../../api/constant'
import store from './../../../store'
import moment from 'moment'
export default {
  name: 'AllowancePayment',
  data () {
    return {
      MINGPAY_SUBSIDY_STATUS: MINGPAY_SUBSIDY_STATUS,
      delayTime: 100,
      formItemLayout: {
        labelCol: {
          xs: { span: 24 },
          sm: { span: 5 }
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 }
        }
      },
      columns: [{
        title: '成员',
        dataIndex: 'recipient',
        width: '200px'
      }, {
        title: '金额',
        dataIndex: 'money',
        scopedSlots: { customRender: 'money' }
      }, {
        title: '津贴类型',
        dataIndex: 'type',
        scopedSlots: { customRender: 'type' }
      },
      {
        title: '经办人',
        dataIndex: 'agentName'
      }, {
        title: '状态',
        dataIndex: 'couponRecordStatus',
        scopedSlots: { customRender: 'couponRecordStatus' }
      }, {
        title: '备注',
        dataIndex: 'remark'
      }, {
        title: '截止时间',
        dataIndex: 'endTime',
        scopedSlots: { customRender: 'endTime' }
      }, {
        title: '操作',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' }
      }],
      form: this.$form.createForm(this),
      visible: false,
      searchSource: {
        UserMessage: {
          avatar: '',
          emplId: '',
          name: ''
        },
        type: '',
        agentName: ''
      },
      recordsList: [],
      pagination: {
        current: 1,
        defaultCurrent: 10,
        defaultPageSize: 10,
        hideOnSinglePage: true,
        total: 0
      },
      config: {
        rules: [{ type: 'object', required: true, message: '请选择时间' }]
      },
      userIdListObj: [],
      departmentIdListObj: [],
      agentList: [],
      startValue: null,
      endValue: null,
      startTime: '',
      endTime: '',
      endOpen: false
    }
  },
  created: function () {
    this.queryCouponRecordList()
    // this.getAgentList()
  },
  methods: {
    // 时间筛选
    moment,
    disabledStartDate (startValue) {
      const endValue = this.endValue
      if (!startValue || !endValue) {
        return false
      }
      return startValue.valueOf() > endValue.valueOf() || startValue.valueOf() >= moment().endOf('day').valueOf()
    },
    disabledEndDate (endValue) {
      const startValue = this.startValue
      if (!endValue || !startValue) {
        return false
      }
      return startValue.valueOf() > endValue.valueOf()
    },
    handleStartOpenChange (open) {
      if (!open) {
        this.endOpen = true
      }
    },
    handleEndOpenChange (open) {
      this.endOpen = open
    },
    onChangeStartValue (date, dateString) {
      this.startTime = dateString
    },
    onChangeEndValue (date, dateString) {
      this.endTime = dateString
    },
    // // 获取收银员列表
    // getAgentList () {
    //   let AgentData = {
    //     userType: '1'
    //   }
    //   $http.get(`/mingpay/v1/isv/cashier/list_cashier_all`, AgentData).then((res) => {
    //     this.agentList = res.data.data
    //   })
    // },
    toAllowanceDetails (record, text, index) {
      this.$router.push({ name: 'allowanceDetails', params: { allowanceDetails: record.grantNumber } })
    },
    selectAgent (value) {
      this.searchSource.agentName = value
    },
    disabledDate (current) {
      // Can not select days before today and today
      console.log(moment().endOf('day'))
      return current < moment(Date.now()).add(-1, 'day')
    },
    // 获取津贴列表
    queryCouponRecordList () {
      let RecordData = {
        currentPage: this.pagination.current,
        pageNumber: this.pagination.defaultPageSize,
        subsidyType: this.searchSource.type,
        agentName: this.searchSource.agentName,
        startTime: this.startTime ? `${this.startTime} 00:00:00` : '',
        endTime: this.endTime ? `${this.endTime} 23:59:59` : ''
      }
      $http.get(`/mingpay/v1/isv/account/list_couponRecord`, RecordData).then((res) => {
        let data = res.data.data
        this.recordsList = data.list
        this.pagination.total = parseInt(data.total)
      })
    },
    // 校验账户充值金额大小和纯数字
    rechargeNum (rule, value, callback) {
      const temp = /^\d+\.?\d{0,2}$/
      if (!temp.test(value) || parseFloat(value) > 10000) {
        callback('请输入正确的金额,最多保留小数点后两位,津贴金额最多为一万元')
        return
      }
      callback()
    },
    // 清理选择帅选人list
    clearUserMessage () {
      this.searchSource.UserMessage = {
        avatar: '',
        emplId: '',
        name: ''
      }
    },
    // 用户头像处理
    avatarCanvasFn (name) {
      let canvas = document.createElement('canvas')
      let con = canvas.getContext('2d')
      let ratio = this.getPixelRatio(con)
      canvas.style.width = 40 + 'px'
      canvas.style.height = 40 + 'px'
      canvas.width = 40 * ratio
      canvas.height = 40 * ratio
      con.scale(ratio, ratio)
      con.fillStyle = '#1890ff'
      con.fillRect(0, 0, 40, 40)
      con.fillStyle = '#ffffff'
      con.font = '12px Arial'
      con.textAlign = 'center'
      con.fillText(name, 20, 25)
      return canvas.toDataURL()
    },
    // 头像模糊处理
    getPixelRatio (context) {
      var backingStore = context.backingStorePixelRatio ||
        context.webkitBackingStorePixelRatio ||
        context.mozBackingStorePixelRatio ||
        context.msBackingStorePixelRatio ||
        context.oBackingStorePixelRatio ||
        context.backingStorePixelRatio || 1
      return (window.devicePixelRatio || 1) / backingStore
    },
    handleTableChange (pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.queryCouponRecordList()
    },
    // 搜索条件津贴类型
    selectHandType (value) {
      this.searchSource.type = value
    },
    peopleListStr () {
      let str = ''
      this.userIdListObj.map((item, index) => {
        str = str + item.name + ','
      })
      this.departmentIdListObj.map((item, index) => {
        str = str + item.name + ','
      })
      return str.substring(0, str.length - 1)
    },
    createSubsidy () {
      this.form.validateFields((err, fieldsValue) => {
        if (err) {
          this.$message.error('请完整填写津贴相关信息')
          return
        }
        if (this.userIdListObj.length === 0 && this.departmentIdListObj.length === 0) {
          this.$message.error('请完整填写津贴相关信息')
          return
        }
        this.visible = false
        store.dispatch('setSpinning', true)
        // Should format date value before submit.
        const values = {
          ...fieldsValue,
          'date-picker': fieldsValue['date-picker'].format('YYYY-MM-DD')
        }
        let userIdList = []
        let departmentIdList = []
        this.userIdListObj.map((item, index) => {
          userIdList.push(item.emplId)
        })
        this.departmentIdListObj.map((item, inde) => {
          departmentIdList.push(item.id)
        })
        let RecordData = {
          ddUserIds: userIdList,
          ddDeptIds: departmentIdList,
          money: values.orderPrice,
          endTime: `${values['date-picker']} 23:59:59`,
          remark: values.remark,
          subsidyEnumType: values.select
        }
        $http.get(`/mingpay/v1/isv/account/batch_create_subsidy`, RecordData).then((res) => {
          if (res.data.resultCode === 0) {
            this.form.resetFields()
            this.userIdListObj = []
            this.departmentIdListObj = []
            this.$message.success(res.data.data)
            this.queryCouponRecordList()
          }
        })
      })
    },
    changeModel () {
      this.visible = !this.visible
    },
    choosePeople () {
      config.ddready('ddchoose').then((res) => {
        this.userIdListObj = res.users
        this.departmentIdListObj = res.departments
        this.form.getFieldsValue().peopleList = 'ok'
      })
    },
    search () {
      this.pagination.current = 1
      this.queryCouponRecordList()
    }
  }
}
</script>

<style lang="less" scoped>
.searchBox{
  display: flex;
  align-items: center;
  margin-bottom: 20px;
}
.searchBox > input {
  margin-right: 20px;
  max-width: 180px;
}
.operationTable a{
  margin-right: 8px;
}
.searchUserMessage{
  width: 100%;
  display: flex;
  flex-direction: column;
  justify-content: center;
  font-size: 12px;
  padding: 8px 8px;
  border: 1px solid #cccccc;
  margin-bottom: 15px;
  border-radius: 8px;
  position: relative;
}
.searchUserMessage img{
  width: 32px;
  height: 32px;
  border-radius: 50%;
  margin-bottom: 8px;
}
.positionDiv{
  height: 12px;
  width: 12px;
  transform:rotate(45deg);
  border-left: 1px solid #cccccc;
  border-top: 1px solid #cccccc;
  position: absolute;
  top: -7px;
  left: 30px;
  background: white;
  z-index: 99;
}
.clearUserMessage{
  position: absolute;
  right: 10px;
}
.peopleBox{
  width: 100%;
  border: 1px solid #d9d9d9;
  min-height: 40px;
  border-radius: 4px;
  padding: 4px 11px;
  font-size: 14px;
  line-height: 1.5;
  cursor: pointer;
}
</style>