<template>
  <a-card :bordered="false" class="userManage-page-info">
    <div class="userManage-search">
      <a-form layout="inline" v-bind="formItemLayout" @keyup.enter.native="$refs.table.refresh(true)">
        <a-row :gutter="20">
          <a-col :span="5">
            <a-form-item label="用户名称" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <a-input allowClear v-model.trim="queryParam.name" placeholder="请输入用户名称" id="userList-name" :maxLength="30" />
            </a-form-item>
          </a-col>
          <a-col :span="5">
            <a-form-item label="手机号码" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <a-input allowClear v-model.trim="queryParam.phone" placeholder="请输入手机号码" :maxLength="11" id="userList-phone" />
            </a-form-item>
          </a-col>
          <a-col :span="5">
            <a-form-item label="所属商户" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <a-select
                placeholder="请选择"
                allowClear
                v-model="queryParam.orgCode"
                :showSearch="true"
                option-filter-prop="children"
                :filter-option="filterOption"
                @focus="handleFocus"
                @blur="handleBlur"
                @change="handleChange">
                <a-select-option v-for="item in optionData" :key="item.orgCode" :value="item.orgCode">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="5">
            <a-form-item label="用户状态" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <v-select code="ENABLE_FLAG" v-model="queryParam.loginFlag" allowClear placeholder="请选择状态" id="userList-check-enable-state"></v-select>
            </a-form-item>
          </a-col>
          <a-col :span="4">
            <a-button type="primary" @click="$refs.table.refresh(true)" id="userList-handSubmit" style="margin-right: 10px;">查询</a-button>
            <a-button type="" @click="reset" id="userList-reset">重置</a-button>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <div class="table-operator">
      <a-button
        type="primary"
        icon="plus"
        @click="openModal"
        id="userList-openModal"
        v-hasPermission="'B_userManage_add'"
        style="margin-top: 18px;">新增</a-button>
    </div>

    <s-table
      ref="table"
      size="default"
      rowKey="id"
      :columns="columns"
      :data="loadData"
      bordered>
      <span slot="status" slot-scope="text, record">
        <a-switch
          v-hasPermission="'B_userManage_enable'"
          checkedChildren="启用"
          unCheckedChildren="禁用"
          v-model="record.loginFlag"
          @change="changeFlagHandle(text, record)"
          id="userList-changeFlagHandle" />
        <span v-if="!$hasPermissions('B_userManage_enable')">--</span>
      </span>
      <span slot="action" slot-scope="text, record">
        <a-icon type="qrcode" title="查看二维码" @click="getQrCode(record)" :style="{ fontSize: '20px', color: '#008000', padding: '0 10px' }" />
        <a-icon
          v-if="$hasPermissions('B_userManage_resetPwd') && record.loginFlag==1"
          type="unlock"
          title="重置密码"
          class="actionBtn icon-orange"
          @click="resetPassword(record)" />
        <a-icon v-if="$hasPermissions('B_userManage_edit')" type="edit" title="编辑" class="actionBtn icon-blues" @click="handleEdit(record)" />
        <a-icon
          v-if="$hasPermissions('B_userManage_del') && record.loginFlag==0"
          type="delete"
          title="删除"
          class="actionBtn icon-red"
          @click="delect(record)" />
        <span v-if="!$hasPermissions('B_userManage_edit') && !($hasPermissions('B_userManage_resetPwd') && record.loginFlag==1) && !($hasPermissions('B_userManage_del') && record.loginFlag==0) ">--</span>
      </span>
    </s-table>
    <userModal :visible="showModal" @refresh="$refs.table.refresh(true)" :itemId="itemId" @close="cancel"></userModal>
    <!-- 查看二维码 -->
    <a-modal
      class="qrCodeModal"
      title="查看二维码"
      :width="500"
      :footer="null"
      :destroyOnClose="true"
      @cancel="isQrCodeModal = false"
      v-model="isQrCodeModal">
      <img :src="qrCode" width="400" height="400" class="qrCode" />
      <p class="info">邀请人：{{ this.name }}{{ this.phone }}</p>
      <a-button type="primary" class="downQrCode" @click="downloadCode">下载二维码</a-button>
    </a-modal>
  </a-card>
</template>

<script>
import {
  STable,
  VSelect
} from '@/components'
import userModal from './userModal.vue'
import {
  sellerList,
  resetPSD,
  updateEnableStatus,
  getPowerUserList,
  delectUserPower,
  qRCode
} from '@/api/userManage.js'
import QRCode from 'qrcode'
export default {
  name: 'UserManage',
  components: {
    STable,
    VSelect,
    userModal
  },
  data () {
    return {
      formItemLayout: {
        labelCol: {
          span: 7
        },
        wrapperCol: {
          span: 17
        }
      },
      // 查询参数
      queryParam: {
        name: '',
        phone: '',
        loginFlag: '',
        orgCode: undefined
      },
      showModal: false,
      itemId: null, // 编辑行id
      qrCode: '', //  小程序码
      isQrCodeModal: false, //  查看小程序码   弹框展示状态
      optionData: [],
      name: '', // 受邀人姓名
      phone: '', // 受邀人电话
      // 表头
      columns: [{
        title: '序号',
        dataIndex: 'no',
        width: 60,
        align: 'center'
      },
      {
        title: '创建时间',
        dataIndex: 'createDate',
        width: 150,
        align: 'center'
      },
      {
        title: '用户名称',
        dataIndex: 'name',
        width: 100,
        align: 'center'
      },
      {
        title: '手机号码',
        dataIndex: 'phone',
        width: 100,
        align: 'center'
      },
      {
        title: '所属商户',
        dataIndex: 'org.name',
        width: 100,
        align: 'center'
      },
      {
        title: '状态',
        width: 100,
        align: 'center',
        scopedSlots: {
          customRender: 'status'
        }
      },
      {
        title: '操作',
        width: 100,
        align: 'center',
        scopedSlots: {
          customRender: 'action'
        }
      }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        return getPowerUserList(Object.assign(parameter, this.queryParam)).then(res => {
          const no = (res.data.pageNo - 1) * res.data.pageSize
          for (let i = 0; i < res.data.list.length; i++) {
            const _item = res.data.list[i]
            _item.no = no + i + 1
            _item.loginFlag = _item.loginFlag + '' === '1'
          }
          return res.data
        })
      }
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.getSellerList()
    })
  },
  methods: {
    handleChange (value) {
      console.log(`selected ${value}`)
    },
    handleBlur () {
      console.log('blur')
    },
    handleFocus () {
      console.log('focus')
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    cancel () {
      this.itemId = null
      this.showModal = false
    },
    // 获取合作商数据
    getSellerList () {
      sellerList().then(res => {
        if (res.status == 200) {
          this.optionData = res.data || []
        }
      })
    },

    // 刷新列表
    refreshTable () {
      this.$refs.table.refresh(true)
    },
    // 新建
    openModal () {
      this.showModal = true
      this.itemData = {}
    },
    // 重置
    reset () {
      this.queryParam.name = ''
      this.queryParam.phone = ''
      this.queryParam.loginFlag = ''
      this.queryParam.orgCode = undefined
      this.refreshTable()
    },
    // 查看二维码
    getQrCode (item) {
      console.log(item)
      const _this = this
      _this.name = item.name
      _this.phone = item.phone
      const opts = {
        errorCorrectionLevel: 'H',
        type: 'image/jpeg',
        quality: 0.3,
        margin: 1.5,
        width: 120,
        color: {
          dark: '#000000',
          light: '#ffffff'
        }
      }
      _this.shName = item.name + item.phone
      console.log(item.encryptedPartnerNo)
      qRCode({ id: item.id }).then(res => {
        if (res.status == 200) {
          const url = res.data
          QRCode.toDataURL(url, opts, function (err, url) {
            _this.qrCode = url
            _this.isQrCodeModal = true
          })
        }
      })
      // if (url) {
      //   QRCode.toDataURL(url, opts, function (err, url) {
      //     _this.qrCode = url
      //     _this.isQrCodeModal = true
      //   })
      // }
    },
    // 查看小程序码
    // getQrCode (item) {
    //   storeQrCode({ id: item.id, deviceNo: item.deviceNos.split(',')[0] }).then(res => {
    //     if (res.status == 200) {
    //       this.qrCode = 'data:image/png;base64,' + res.data
    //       this.isQrCodeModal = true
    //     } else {
    //       this.qrCode = ''
    //       this.$message.error(res.message)
    //     }
    //   })
    // },
    //  下载小程序码
    downloadCode () {
      const link = document.createElement('a')
      link.href = this.qrCode
      link.download = this.shName + '.jpg'
      link.click()
    },
    // 重置密码
    resetPassword (row) {
      resetPSD({
        id: row.id
      }).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
        }
      })
    },
    // 删除
    delect (row) {
      const _this = this
      this.$confirm({
        title: '警告',
        centered: true,
        content: '删除后无法恢复，确认删除?',
        okText: '确定',
        cancelText: '取消',
        onOk () {
          delectUserPower({
            id: row.id
          }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
            }
          })
        }
      })
    },
    handleEdit (row) {
      console.log(row, 'row')
      this.itemId = row.id
      this.showModal = true
    },
    // 修改状态
    changeFlagHandle (text, record) {
      const _data = {
        id: record.id,
        flag: record.loginFlag ? '1' : '0'
      }
      updateEnableStatus(_data).then(res => {
        if (res.status + '' === '200') {
          this.$message.success(res.message)
        } else {
          record.loginFlag = !record.loginFlag
        }
      })
    }
  }
}
</script>
<style lang="less">
  .userManage-page-info {
    .userManage-search {
      .ant-form-inline .ant-form-item {
        width: 100%;
      }
    }
  }
  .qrCodeModal {
  	.qrCode {
  		display: block;
  		max-width: 100%;
  		margin: 0 auto;
  	}
  	.downQrCode {
  		display: block;
  		margin: 40px auto 30px;
  	}
    .info{
      text-align: center;
      margin: 15px 0 0 0;
    }
  }
</style>
