<template>
  <div class="user-list-con">
    <Card>
      <div class="search-con">
        <Input
          placeholder="请输入商户ID"
          class="search-input"
          v-model="searchContent.merchantId"
          style="width: 200px"
          clearable
        />
        <Input
          placeholder="请输入登录账号"
          class="search-input"
          v-model="searchContent.account"
          style="width: 200px"
          clearable
        />
        <Input
          placeholder="请输入联系人"
          class="search-input"
          v-model="searchContent.linkMan"
          style="width: 200px"
          clearable
        />
        <ButtonGroup class="search-btngroup">
          <Button @click="handleSearch" type="primary">查找</Button>
          <Button type="primary" @click="handleRefresh">
            <Icon type="md-refresh" />
          </Button>
        </ButtonGroup>
      </div>
      <tables
        ref="tables"
        editable
        pagable
        v-model="tableData"
        :columns="columns"
        :currentPage="searchContent.pageNum"
        :pageSize="searchContent.pageSize"
        :totalSize="totalSize"
        :loading="loading"
        @on-change="handleCurrentChange"
      />
    </Card>
    <Modal v-model="modal" title="编辑等级：" @on-ok="changeLevel">
        <div class="modal-form-con" style="padding-right:30px">
          <Form ref="formInline" :model="formData" label-position="right" :label-width="100">
              <FormItem label="手机号:">
                  <Input type="text" v-model="formData.registerPhone" readonly></Input>
              </FormItem>
              <FormItem label="联系人:">
                  <Input type="text" v-model="formData.linkMan" readonly></Input>
              </FormItem>
              <FormItem label="商家等级:">
                  <Select v-model="formData.levelNo">
                      <Option v-for="(item,index) in MerchantLevelObj" :key="index" :value="item.levelNo">{{item.levelName}}</Option>
                  </Select>
              </FormItem>
          </Form>
        </div>
    </Modal>
  </div>
</template>

<script>
import Tables from '_c/tables'
import { formatTime } from '@/libs/tools'
import { MerchantType, MerchantTypeObject, MerchantStatusObject, MerchantStatus } from '@/enums'
export default {
  inject: ['reload'],
  components: {
    Tables
  },
  computed: {
    isBrand () {
      return this.$store.getters.isBrand
    }
  },
  data () {
    return {
      MerchantType,
      MerchantTypeObject,
      MerchantStatus,
      MerchantStatusObject,
      MerchantLevelObj:{},
      searchContent: {
        merchantId: '',
        account: '',
        linkMan: '',
        pageNum: 1,
        pageSize: 10
      },
      createTime: [],

      columns: [
        { title: 'UID', key: 'merchantId', align: 'left', minWidth: 180 },
        { title: '手机号', key: 'registerPhone', align: 'center', width: 120 },
        {
          title: '联系人',
          key: 'linkMan',
          align: 'center',
          minWidth: 100,
          render: (h, params) => {
            return h('span', params.row.linkMan ? params.row.linkMan : '--')
          }
        },
        { title: '身份证',
          key: 'registerCode',
          align: 'center',
          minWidth: 140,
          render: (h, params) => {
            let idCard = params.row.idCard
            let emptySpan = h('span', '--')
            let labelSpan = h('span', idCard)
            let searchIdCard = h('Icon', {
              props: {
                size: 20,
                type: 'ios-eye-off',
                color: '#000'
              },
              style: {
                marginLeft: '5px',
                cursor: 'pointer'
              }
            })
            let contentDiv = h(
              'div',
              {
                style: {
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  height: '30px'
                }
              },
              // this.isBrand ? [labelSpan] : [labelSpan, clearIcon]
              [labelSpan]
            )
            const statusPoptip = h(
              'Poptip',
              {
                props: {
                  confirm: true,
                  title: `确定要查询当前商户idCard吗?`,
                  transfer: true
                },
                on: {
                  'on-ok': () => {
                    this.handleSeacrhId(params.row)
                  }
                }
              },
              [searchIdCard]
            )

            return idCard ? [contentDiv, statusPoptip] : emptySpan
          }
        },
        { title: '商户类型',
          key: 'type',
          align: 'center',
          width: 140,
          render: (h, params) => {
            let statusObj = MerchantTypeObject[params.row.type]
            return h('span', statusObj ? statusObj.name : '--')
          }
        },
        { title: '商户等级',
          key: 'level',
          align: 'center',
          width: 140,
          render: (h, params) => {
            let statusObj = this.MerchantLevelObj[params.row.level] || {}
            return h('span', statusObj.levelName)
          }
        },
        { title: '状态',
          key: 'status',
          align: 'center',
          width: 140,
          render: (h, params) => {
            let statusObj = MerchantStatusObject[params.row.status]
            return h('Tag',
              {
                props: {
                  color: statusObj.color
                }
              },
              statusObj ? statusObj.name : '--'
            )
          }
        },
        { title: '注册时间',
          key: 'registerTime',
          align: 'center',
          width: 160,
          render: (h, params) => {
            return h('span', formatTime(params.row.registerTime))
          }
        },
        { title: '最近登录时间',
          key: 'lastLoginTime',
          align: 'center',
          width: 160,
          render: (h, params) => {
            return h('span', params.row.lastLoginTime ? formatTime(params.row.lastLoginTime) : '--')
          }
        },
        {
          title: '操作',
          key: 'status',
          align: 'left',
          fixed: 'right',
          width: 240,
          render: (h, params) => {
            let status = params.row.status
            const statusBtn = h(
              'Button',
              {
                props: {
                  type: params.row.status == MerchantStatus.NORMAL ? 'primary' : 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '10px'
                }
              },
              status == MerchantStatus.NORMAL ? '锁 定' : '解 锁'
            )
            const statusPoptip = h(
              'Poptip',
              {
                props: {
                  confirm: true,
                  title: `确定要 ${
                    status == MerchantStatus.NORMAL ? '锁定' : '解锁'
                  } 该用户？`,
                  transfer: true
                },
                on: {
                  'on-ok': () => {
                    this.handleUpdateStatus(params.row)
                  }
                }
              },
              [statusBtn]
            )
            const resetPwd = h(
              'Button',
              {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                style: {
                  marginRight: '10px'
                }
              },
              '重置登录密码'
            )
            const resetPoptip = h(
              'Poptip',
              {
                props: {
                  confirm: true,
                  title: `确定要重置登录密码吗？`,
                  transfer: true
                },
                on: {
                  'on-ok': () => {
                    this.handleResetPwd(params.row)
                  }
                }
              },
              [resetPwd]
            )
            const editBtn = h(
              'Button',
              {
                props: {
                  type: 'primary',
                  size: 'small'
                },
                on: {
                  click: ()=>{
                    this.handleEdit(params)
                  }
                },
                style: {
                  marginRight: '5px'
                }
              },
              '编 辑'
            )
           let operateInfo = (status == MerchantStatus.NORMAL || status == MerchantStatus.FORZEN) ? [statusPoptip, resetPoptip,editBtn] : '——'
            return h('div', operateInfo)
          }
        }
      ],
      tableData: [],
      totalSize: 0,
      loading: false,

      newRecommend: '',
      modal:false,
      formData:{
        registerPhone:"",
        linkMan:'',
        merchantId:'',
        levelNo:1,
      }
    }
  },
  methods: {
    _getMerchantSettinglist() {
      this.api({
        apiName: 'getMerchantSettinglist',
        success: (res) => {
          this.MerchantLevelObj={}
          for(let item of res.data){
            this.MerchantLevelObj[item.levelNo]={
              levelName:item.levelName,
              levelNo:item.levelNo
            }
          }
        }
      })
    },
    requestData () {
      this.loading = true
      this.searchContent.merchantId = this.searchContent.merchantId.replace(/\s+/g, '')
      this.searchContent.account = this.searchContent.account.replace(/\s+/g, '')
      this.searchContent.linkMan = this.searchContent.linkMan.replace(/\s+/g, '')
      this.api({
        apiName: 'getMerchantList',
        postdata: this.searchContent,
        success: (res) => {
          this.totalSize = res.data.total
          this.tableData = res.data.records
        },
        complete: () => {
          this.loading = false
        }
      })
    },
    handleDateChange (createTime) {
      if (
        createTime &&
          createTime.length == 2 &&
          createTime[0] &&
          createTime[1]
      ) {
        this.searchContent.startTime = new Date(createTime[0]).getTime()
        this.searchContent.endTime =
            new Date(createTime[1]).getTime() + 24 * 60 * 60 * 1000 - 1
      } else {
        this.searchContent.startTime = ''
        this.searchContent.endTime = ''
      }
    },
    handleSearch () {
      this.searchContent.pageNum = 1
      this.requestData()
    },
    handleRefresh () {
      this.reload()
    },
    handleCurrentChange (pageNum) {
      this.searchContent.pageNum = pageNum
      this.requestData()
    },

    handleSeacrhId (row) {
      let registerPhone = row.registerPhone
      this.api({
        apiName: 'searchMerchangIdCard',
        postdata: { registerPhone },
        success: (res) => {
          console.log(res.data)
          this.$Modal.success({
            title: 'idCard',
            content: res.data
          })
        }
      })
    },

    handleUpdateRecommend (row, newRecommend) {
      if (!newRecommend) {
        this.$Notice.warning({ title: '邀请人UID不能为空！' })
        return
      }

      let uid = row.uid
      this.api({
        apiName: 'updateUserInviteCode',
        postdata: {
          uid,
          inviteUid: newRecommend
        },
        success: () => {
          row.recommend = newRecommend
          this.$Notice.success({ title: '修改成功！' })
        }
      })
    },
    handleUpdateStatus (row) {
      let merchantId = row.merchantId
      let lock =
          row.status == MerchantStatus.NORMAL ? MerchantStatus.FORZEN : MerchantStatus.NORMAL

      this.api({
        apiName: 'updateMerchantStatus',
        postdata: {
          merchantId,
          lock
        },
        success: () => {
          row.status = status
          this.requestData()
          this.$Notice.success({ title: '修改成功！' })
        }
      })
    },
    handleResetPwd (row) {
      let account = row.registerPhone
      this.api({
        apiName: 'resetMerchantPwd',
        postdata: account,
        success: (res) => {
          this.$Notice.success({ title: '重置成功！' })
          this.requestData()
        }
      })
    },
    handleEdit(params){
      if(!this.MerchantLevelObj){
        this.$Notice.warning({ title: '请前往商户设置新建等级！' })
        return
      }
      this.modal=true
      this.formData={
        registerPhone:params.row.registerPhone,
        linkMan:params.row.linkMan,
        merchantId:params.row.merchantId,
        levelNo:params.row.level,
      }
    },
    changeLevel(){
      if(typeof this.formData.levelNo!=='number'){
        this.$Notice.warning({ title: '请选择商家等级' })
        return
      }
      this.api({
        apiName:'editLevel',
        postdata: {
          merchantId:this.formData.merchantId,
          levelNo:this.formData.levelNo
        },
        success: (res) => {
          this.$Notice.success({ title: '编辑成功！' })
          this.requestData()
        }
      })
    }
  },
  created () {
    this.requestData()
    this._getMerchantSettinglist()
  }
}
</script>
<style lang="less">
  .user-list-con .search-con {
    padding: 10px 0;
    .search {
      &-col {
        display: inline-block;
        width: 150px;
        margin-right: 5px;
      }
      &-input {
        display: inline-block;
        width: 150px;
        margin-right: 5px;
      }
      &-date {
        margin-right: 5px;
      }
      &-btngroup {
        margin-right: 5px;
      }
    }
  }
</style>
