<template>
    <div class="AccountManagement">
      <div class="searchBox">
        <a-input placeholder="选择成员" @click="choosePeople" style="width: 120px"/>
        <a-input placeholder="输入卡号" v-model="searchSource.cardNum" style="width: 120px"/>
        <a-select defaultValue="卡片状态" style="width: 120px;margin-right: 20px;" @change="selectHandleChangeCard">
          <a-select-option value="ACTIVE">已绑卡</a-select-option>
          <a-select-option value="NOT_EXIST">未绑卡</a-select-option>
          <a-select-option value="UNACTIVE">冻结</a-select-option>
        </a-select>
        <a-select defaultValue="账户状态" style="width: 120px;margin-right: 20px;" @change="selectHandleChangeAccount">
          <a-select-option value="ACTIVE">使用中</a-select-option>
          <a-select-option value="LOG_OFF">冻结并结现</a-select-option>
        </a-select>
        <a-button type="primary" @click="queryAccountList()">查询</a-button>
      </div>
      <div class="searchUserMessage" v-if="searchSource.UserMessage.emplId">
        <div class="positionDiv"></div>
        <div class="clearUserMessage"><a href="javascript:;" @click="clearUserMessage">清除</a></div>
        <img v-if="searchSource.UserMessage.avatar" :src="searchSource.UserMessage.avatar" :alt="searchSource.UserMessage.name"/>
        <img v-else :src="this.avatarCanvasFn(searchSource.UserMessage.name)" :alt="searchSource.UserMessage.name">
        <span>{{ searchSource.UserMessage.name }}</span>
      </div>
      <a-table :columns="columns" :dataSource="accountList" size="default" rowKey="userId" :pagination="pagination" @change="handleTableChange">
        <span slot="name">姓名</span>
        <span slot="departmentNameList" slot-scope="departmentNameList">
          {{ departmentNameListToStr(departmentNameList) }}
        </span>
        <span slot="realityBalance">余额</span>
        <span slot="cardNo" slot-scope="cardNo, record">
          {{ cardNo ? cardNo : '未绑卡' }}
          <br/>
          {{ cardNo ? record.cardStatus === 'UNACTIVE' ? '已冻结' : '使用中' : ''}}
        </span>
        <span slot="status" slot-scope="status">
          {{ status === MINGPAY_ACCOUNT_STATUS.ACTIVE ? '使用中' : '已注销并结现' }}
        </span>
        <span slot="action" slot-scope="text, record, index" class="operationTable">
          <a href="javascript:;" @click="ToViewAllowances(record)">查看津贴</a>
          <a v-if="record.status = MINGPAY_ACCOUNT_STATUS.ACTIVE" href="javascript:;" @click="showModal(record.userId, record.name, index)">充值</a>
          <a-dropdown v-if="record.status = MINGPAY_ACCOUNT_STATUS.ACTIVE">
            <a class="ant-dropdown-link" href="javascript:;">
              更多操作 <a-icon type="down" />
            </a>
            <a-menu slot="overlay">
              <a-menu-item v-if="record.cardStatus === MINGPAY_ACCOUNT_STATUS.ACTIVE && record.cardNo ">
                <a href="javascript:;" @click="showConfirm(record.userId, 1, index)">冻结实体卡</a>
              </a-menu-item>
              <a-menu-item v-if="record.cardStatus === MINGPAY_ACCOUNT_STATUS.UNACTIVE && record.cardNo">
                <a href="javascript:;" @click="showConfirm(record.userId, 2, index)">解冻实体卡</a>
              </a-menu-item>
              <a-menu-item v-if="record.cardNo">
                <a href="javascript:;" @click="confimBindSure(record.userId, index)">解绑实体卡</a>
              </a-menu-item>
              <a-menu-item v-else>
                <a href="javascript:;" @click="changeVisible2(record.userId, index)">绑定实体卡</a>
              </a-menu-item>
              <a-menu-item v-if="record.status != MINGPAY_ACCOUNT_STATUS.LOG_OFF">
                <a href="javascript:;" @click="showConfirm(record.userId, 3, index)">注销并结现</a>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>
      </a-table>
      <a-modal title="绑定实体卡" v-model="visible2" @ok="cardOperation(2)">
        <a-form :form="updateBindCardStatusForm">
          <a-form-item label="实体卡号" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }" >
            <a-input v-decorator="['cardNo', {rules: [{ required: true, message: '请填写正确的实体卡号!' }, {validator: bindCardNum}]}]"/>
          </a-form-item>
        </a-form>
      </a-modal>
      <a-modal title="现金充值" v-model="visible" @ok="internalRecharge()">
        <a-form :form="form">
          <a-form-item label="充值金额" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }" >
            <a-input
              v-decorator="['orderPrice',{rules: [{required: true, message: '充值金额不能为空'}, {validator: rechargeNum}]}]"
            />
          </a-form-item>
          <a-form-item label="备注" :label-col="{ span: 5 }" :wrapper-col="{ span: 12 }" >
            <a-textarea v-decorator="['remark', {rules: [{ required: true, message: '备注不能为空' }]}]"/>
          </a-form-item>
        </a-form>
      </a-modal>
      <!-- 账户管理 -->
      <!-- <button @click="asd()">鉴权</button> -->
      <!-- <button @click="asd2()"> 免等</button> -->
    </div>
</template>

<script>
import { config } from './../../../api/config.js'
import { $http } from './../../../api/axios.js'
import { MINGPAY_ACCOUNT_STATUS } from './../../../api/constant'
// import { avatarFn } from './../../../api/avatar'
export default {
  name: 'accountManagement',
  components: {},
  data () {
    return {
      visible: false,
      visible2: false,
      formLayout: 'horizontal',
      form: this.$form.createForm(this),
      updateBindCardStatusForm: this.$form.createForm(this),
      MINGPAY_ACCOUNT_STATUS: MINGPAY_ACCOUNT_STATUS,
      data: [],
      pagination: {
        current: 1,
        defaultCurrent: 10,
        defaultPageSize: 10,
        hideOnSinglePage: true,
        total: 0
      },
      columns: [{
        title: '成员',
        dataIndex: 'name',
        width: '90px'
      }, {
        title: '部门',
        dataIndex: 'departmentNameList',
        scopedSlots: { customRender: 'departmentNameList' },
        width: '140px'
      }, {
        title: '余额',
        dataIndex: 'realityBalance'
      }, {
        title: '实体卡状态',
        dataIndex: 'cardNo',
        scopedSlots: { customRender: 'cardNo' }
      }, {
        title: '账户状态',
        dataIndex: 'status',
        scopedSlots: { customRender: 'status' }
      }, {
        title: '操作',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' }
      }],
      accountList: [],
      rechargeData: {
        userId: '',
        userName: '',
        orderPrice: '',
        remark: ''
      },
      selsctUserId: '',
      selsctIndex: 0,
      searchSource: {
        ddchoosePeople: {
          userIdList: [],
          departmentIdList: []
        },
        UserMessage: {
          avatar: '',
          emplId: '',
          name: ''
        },
        cardNum: '',
        cardStatus: '',
        accountStatus: ''
      }
    }
  },
  watch: {},
  computed: {},
  created: function () {
    this.queryAccountList()
  },
  methods: {
    // 获取账户列表
    queryAccountList () {
      const _that = this
      let AccountData = this.$qs.stringify({
        pageNum: this.pagination.current,
        numPerPage: this.pagination.defaultPageSize,
        departmentIdList: this.searchSource.ddchoosePeople.departmentIdList,
        userIdList: this.searchSource.ddchoosePeople.userIdList,
        status: this.searchSource.accountStatus,
        cardNo: this.searchSource.cardNum,
        cardStatus: this.searchSource.cardStatus,
        orgId: sessionStorage.getItem('corpId')
      })
      $http.get(`/v1/account/queryAccountList?${AccountData}`).then((res) => {
        _that.accountList = res.data.data.recordList
        _that.pagination.total = parseInt(res.data.data.totalCount)
        console.log(_that)
        console.log(_that.accountList)
      })
    },
    // 搜索条件,卡片和账户状态
    selectHandleChangeCard (value) {
      console.log(value)
      this.searchSource.cardStatus = value
    },
    selectHandleChangeAccount (value) {
      this.searchSource.accountStatus = value
    },
    // 选人组件调用
    choosePeople () {
      config.ddready('ddchoose').then((res) => {
        console.log(res)
        let userIdListObj = []
        let departmentIdListObj = []
        res.departments.map((item, index) => {
          departmentIdListObj.push(item.id)
        })
        res.users.map((item, index) => {
          userIdListObj.push(item.emplId)
        })
        this.searchSource.ddchoosePeople.departmentIdList = departmentIdListObj
        this.searchSource.ddchoosePeople.userIdList = userIdListObj
      })
    },
    // 校验账户充值金额大小和纯数字
    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
    },
    // 绑定实体卡号校验,仅字符串和数字
    bindCardNum (rule, value, callback) {
      var re = /^[0-9a-zA-Z]*$/
      if (!re.test(value)) {
        callback('实体卡卡号必须由数字和字母组成')
        return
      }
      callback()
    },
    // 绑定实体卡modal切换
    changeVisible2 (str, index) {
      this.visible2 = !this.visible2
      this.selsctUserId = str
      this.selsctIndex = index
    },
    // 分页
    handleTableChange (pagination, filters, sorter) {
      this.pagination.current = pagination.current
      this.queryAccountList()
    },
    // table部门表格字符串处理
    departmentNameListToStr (str) {
      let departmentNameListStr = ''
      if (str.length !== 0) {
        str.map((data) => {
          departmentNameListStr = `${departmentNameListStr}${data},`
        })
      }
      departmentNameListStr = departmentNameListStr.substring(0, departmentNameListStr.length - 1)
      return departmentNameListStr
    },
    // 查看津贴
    ToViewAllowances (str) {
      console.log(str.userId)
      this.$router.push({ name: 'viewAllowances', params: { userId: str.userId } })
    },
    // 内部充值接口
    internalRecharge () {
      let _that = this
      this.rechargeData.orderPrice = this.form.getFieldsValue().orderPrice
      this.rechargeData.remark = this.form.getFieldsValue().remark
      this.rechargeData.orgId = sessionStorage.getItem('corpId')
      let rechargeData = this.$qs.stringify(this.rechargeData)
      $http.get(`/v1/charge/charge?${rechargeData}`).then((res) => {
        console.log(res.data.message)
        if (res.data.message === 'SUCCESS') {
          this.visible = false
          this.form.resetFields()
          this.$message.success('充值成功')
        } else {
          this.$message.success(res.data.message)
        }
      }).catch((err) => {
        console.log(err)
        this.$message.error('充值失败')
      })
    },
    // 充值modal
    showModal (userId, userName, index) {
      this.rechargeData.userId = userId
      this.rechargeData.userName = userName
      this.selsctIndex = index
      this.visible = true
    },
    // 账户操作和卡片操作
    accountOperation (type, userId, status, index) {
      let accountOperationData = this.$qs.stringify({
        userId: userId,
        status: status,
        orgId: sessionStorage.getItem('corpId')
      })
      let url = type === 3 ? 'update_account_status' : 'update_card_status'
      $http.get(`/v1/account/${url}?${accountOperationData}`).then((res) => {
        if (res.data.message === 'SUCCESS') {
          let dataSource = [...this.accountList]
          if (type === 1 || type === 2) {
            dataSource[index].cardStatus = status
          } else if (type === 3) {
            dataSource[index].status = status
          }
          this.accountList = dataSource
          this.$message.success('操作成功')
        }
      }).catch(() => {
        this.$message.error('修改失败')
      })
    },
    // binding,unbinding二次确认
    confimBindSure (userId, index) {
      this.selsctUserId = userId
      this.selsctIndex = index
      const _that = this
      this.$confirm({
        title: '确认要对该账户实体卡解除绑定么?',
        content: '解除绑定后,该实体卡将不能付款',
        onOk () {
          _that.cardOperation(1)
        }
      })
    },
    // 冻结,解冻,注销结现二次确认
    showConfirm (userId, str, index) {
      let title = ''
      let content = ''
      let status = ''
      let url = ''
      const _that = this
      // 1冻结,2解冻,3注销并结现
      switch (str) {
        case 1:
          title = '确认要对该账户实体卡进行冻结操作么?'
          content = '冻结后二维码可使用付款,实体卡片不能付款,若想再次使用实体卡请先解冻'
          status = MINGPAY_ACCOUNT_STATUS.UNACTIVE
          url = ''
          break
        case 2:
          title = '确认要对该账户实体卡进行解冻操作么?'
          content = '解冻后二维码与实体卡片均可正常使用'
          status = MINGPAY_ACCOUNT_STATUS.ACTIVE
          url = ''
          break
        case 3:
          title = '确认要对该账户进行注销并结现操作么?'
          content = '注销并结现后二维码与实体卡片均不能在使用'
          status = MINGPAY_ACCOUNT_STATUS.LOG_OFF
          url = ''
      }
      this.$confirm({
        title: title,
        content: content,
        onOk () {
          _that.accountOperation(str, userId, status, index)
        }
      })
    },
    // 绑卡解绑操作
    cardOperation (type) {
      let cardOperationData = ''
      const cardNo = this.updateBindCardStatusForm.getFieldsValue().cardNo
      if (type === 2) {
        cardOperationData = this.$qs.stringify({
          cardNo: this.updateBindCardStatusForm.getFieldsValue().cardNo,
          userId: this.selsctUserId,
          orgId: sessionStorage.getItem('corpId')
        })
      } else if (type === 1) {
        cardOperationData = this.$qs.stringify({
          cardNo: '',
          userId: this.selsctUserId,
          orgId: sessionStorage.getItem('corpId')
        })
      }
      $http.get(`/v1/account/update_bind_card_status?${cardOperationData}`).then((res) => {
        if (res.data.message === 'SUCCESS') {
          let dataSource = [...this.accountList]
          if (type === 2) {
            dataSource[this.selsctIndex].cardNo = cardNo
          } else if (type === 1) {
            dataSource[this.selsctIndex].cardNo = ''
          }
          this.accountList = dataSource
          this.visible2 = false
          this.$message.success('操作成功')
        } else {
          this.$message.error(res.data.message)
        }
      }).catch((err) => {
        console.log(err)
      })
    }
  },
  mounted () {}
}
</script>

<style lang="less" scoped>
.searchBox{
  display: flex;
  margin-bottom: 15px;
}
.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;
}
</style>