<template>
  <a-card :bordered="false" class="userManageList-table-page-search-wrapper">
    <div class="userManageList-searchForm">
      <a-form-model :model="queryParam" ref="queryForm" layout="inline" v-bind="formItemLayout" @keyup.enter.native="refresh">
        <a-row :gutter="20">
          <a-col :span="6">
            <a-form-model-item label="注册时间" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <a-range-picker
                id="network-time"
                v-model="registerTime"
                :format="dateFormat"
                :placeholder="['开始时间','结束时间']"
                :disabledDate="disabledDate"
                @change="onChangeregisterTime" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="最后投递时间" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <a-range-picker
                id="network-time"
                v-model="lastDeliverTime"
                :format="dateFormat"
                :placeholder="['开始时间','结束时间']"
                :disabledDate="disabledDate"
                @change="onChangelastDeliverTime" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item prop="mobile" label="用户手机" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <a-input id="userManageList-mobile" allowClear :maxLength="11" v-model="queryParam.mobile" placeholder="请输入用户手机" />
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="乐豆余额" prop="currentGoldMin" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <div class="input-number">
                <a-input-number id="userManageList-inputNumber" v-model="queryParam.currentGoldMin" :max="999999999" />
                <span style="margin:0 11%">-</span>
                <a-input-number id="inputNumber" v-model="queryParam.currentGoldMax" :max="999999999" />
              </div>
            </a-form-model-item>
          </a-col>
        </a-row>
        <a-row :gutter="20">
          <a-col :span="6">
            <a-form-model-item label="账户状态" prop="state" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <v-select
                v-model="queryParam.state"
                id="userManageList-state"
                code="ENABLE_FLAG"
                placeholder="请选择账户状态"
                allowClear></v-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item prop="customerRole" label="用户身份" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <v-select
                v-model="queryParam.customerRole"
                id="userManageList-customerRole"
                code="CUSTOMER_ROLE"
                placeholder="请选择用户身份"
                allowClear></v-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="首次投递网点">
              <a-select
                id="userManageList-firstDeliveryStationNo"
                placeholder="请选择首次投递网点"
                allowClear
                v-model="queryParam.firstDeliveryStationNo"
                :showSearch="true"
                option-filter-prop="children"
                :filter-option="filterOption"
              >
                <a-select-option v-for="item in stationData" :key="item.stationNo" :value="item.stationNo">{{ item.name }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="网点标签">
              <a-select
                style="max-height: 50px;overflow: auto;margin-top: 3px;"
                id="userManageList-labelNo"
                placeholder="请选择网点标签"
                mode="multiple"
                allowClear
                v-model="queryParam.labelNoList"
                :showSearch="true"
                option-filter-prop="children"
                :filter-option="filterOption"
              >
                <a-select-option v-for="item in lableData" :key="item.labelNo" :value="item.labelNo">{{ item.labelName }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="20">
          <a-col :span="6">
            <a-form-model-item label="用户注册方式" prop="introType" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <v-select
                v-model="queryParam.introType"
                id="userManageList-introType"
                code="INTRO_TYPE"
                placeholder="请选择注册方式"
                allowClear></v-select>
            </a-form-model-item>
          </a-col>
          <a-col :span="6">
            <a-form-model-item label="受邀人" prop="userPhone" :label-col="formItemLayout.labelCol" :wrapper-col="formItemLayout.wrapperCol">
              <a-input v-model.trim="queryParam.userPhone" placeholder="请输入受邀人手机号或姓名" id="userManageList-userPhone" @pressEnter="$refs.table.refresh(true)" allowClear/>
            </a-form-model-item>
          </a-col>
          <a-col style="float: right">
            <a-button class="handle-btn serach-btn" id="userManageList-btn-serach" type="primary" @click="refresh">查询</a-button>
            <a-button class="handle-btn" type="" id="userManageList-btn-reset" @click="handleReset">重置</a-button>
            <a-button
              class="export-btn"
              id="userManageList-btn-export"
              :loading="loading"
              @click="handleExport"
              v-hasPermission="'B_user_userManage_export'">导出</a-button>
          </a-col>
        </a-row>
      </a-form-model>
    </div>
    <s-table
      ref="table"
      size="default"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data="loadData"
      :scroll="{ x: 1800}"
      bordered>
      <!--启用禁用 -->
      <template slot="state" slot-scope="text, record">
        <a-switch
          v-hasPermission="'B_user_userManage_enable'"
          checkedChildren="启用"
          unCheckedChildren="禁用"
          id="userManageList-changeFlagHandle"
          :checked="record.state == 1 ? true : false"
          @change="changeFlagHandle(text, record)" />
        <span v-if="!$hasPermissions('B_user_userManage_enable')">--</span>
      </template>
      <!-- 受邀人 -->
      <template slot="person" slot-scope="text,record">
        <p>{{ record.userName }}</p>
        <p>{{ record.userPhone }}</p>
        <p v-if="!record.userName &&!record.userPhone">--</p>
      </template>
      <!-- 操作 -->
      <template slot="action" slot-scope="text, record">
        <a-button id="userManageList-handleUser" type="link" @click="handleUser(record)" v-hasPermission="'B_user_userManage_userDetails'">用户详情</a-button>
        <a-button id="userManageList-handleLd" type="link" @click="handleLd(record)" v-hasPermission="'B_user_userManage_LdDetails'">乐豆明细</a-button>
        <span v-if="!$hasPermissions('B_user_userManage_userDetails') && (!$hasPermissions('B_user_userManage_LdDetails'))">--</span>
      </template>
    </s-table>
  </a-card>

</template>

<script>
import {
  STable,
  VSelect
} from '@/components'
import {
  customerList,
  changeStatus,
  customeExport
} from '@/api/userInfo.js'
import { lableSeleteList, stationSeleteList } from '@/api/labelSetting.js'
import moment from 'moment'
export default {
  name: 'UserManageList',
  components: {
    STable,
    VSelect
  },
  data () {
    return {
      formItemLayout: {
        labelCol: {
          span: 7
        },
        wrapperCol: {
          span: 17
        }
      },
      registerTime: [], // 注册时间
      lastDeliverTime: [], // 最后投递时间
      lableData: [], // 网点标签
      stationData: [], // 首次投递
      dateFormat: 'YYYY-MM-DD',
      // 查询参数
      queryParam: {
        mobile: '', //  用户手机
        state: '', // 账户状态
        customerRole: '', // 用户身份
        currentGoldMin: '', // 乐豆余额最小值
        currentGoldMax: '', // 乐豆余额最大值
        beginDate: null, // 最后投递时间的开始时间
        endDate: null, // 最后投递时间的结束时间
        beginRegisterTime: null, //  注册时间最小值
        endRegisterTime: null, //  注册时间最大值
        labelNoList: [], // 网点标签
        firstDeliveryStationNo: undefined, // 首次投递
        introType: '', // 注册方式
        userPhone: '' // 受邀人
      },
      loading: false, // 导出loading
      // 表头
      columns: [{ title: '序号', dataIndex: 'no', width: 80, align: 'center', fixed: 'left' },
        { title: '用户手机', dataIndex: 'mobile', width: 150, align: 'center' },
        { title: '用户注册方式', dataIndex: 'introTypeDictValue', width: 150, align: 'center', customRender: (text) => { return text || '--' } },
        { title: '受邀人', dataIndex: 'person', width: 150, align: 'center', scopedSlots: { customRender: 'person' } },
        { title: '用户身份', dataIndex: 'customerRoleDictValue', width: 100, align: 'center' },
        { title: '乐豆余额', dataIndex: 'currentGold', width: 100, align: 'center', customRender: (text) => { return text || 0 } },
        { title: '累计乐豆', dataIndex: 'totalGold', width: 100, align: 'center', customRender: (text) => { return text || 0 } },
        { title: '注册时间', dataIndex: 'registerTime', width: 150, align: 'center', customRender: (text) => { return text || '--' } },
        { title: '最后登录时间', dataIndex: 'lastLoginTime', width: 150, align: 'center', customRender: (text) => { return text || '--' } },
        { title: '最后投递时间', dataIndex: 'lastDeliveryTime', width: 150, align: 'center', customRender: (text) => { return text || '--' } },
        { title: '状态', width: 100, dataIndex: 'state', align: 'center', scopedSlots: { customRender: 'state' } },
        { title: '首次投递网点', dataIndex: 'firstDeliveryStationName', width: 150, align: 'center', customRender: (text) => { return text || '--' } },
        { title: '网点标签', dataIndex: 'labelName', width: 150, align: 'center', customRender: (text) => { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 120, align: 'center' }],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        const searchData = Object.assign(parameter, this.queryParam)
        if (this.registerTime && this.registerTime.length) {
          searchData.beginRegisterTime = moment(this.registerTime[0]).format('YYYY-MM-DD 00:00:00')
          searchData.endRegisterTime = moment(this.registerTime[1]).format('YYYY-MM-DD 23:59:59')
        } else {
          searchData.beginRegisterTime = null
          searchData.endRegisterTime = null
        }
        if (this.lastDeliverTime && this.lastDeliverTime.length) {
          searchData.beginDate = moment(this.lastDeliverTime[0]).format('YYYY-MM-DD 00:00:00')
          searchData.endDate = moment(this.lastDeliverTime[1]).format('YYYY-MM-DD 23:59:59')
        } else {
          searchData.beginDate = null
          searchData.endDate = null
        }
        return customerList(searchData).then(res => {
          if (res.status == 200) {
            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.status = _item.status + '' === '1'
            }
            return res.data
          }
        })
      }
    }
  },
  mounted () {
    this.getlableSeleteList()
    this.getStationSeleteList()
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.$refs.queryForm.resetFields()
      vm.registerTime = []
      vm.lastDeliverTime = []
    })
  },
  methods: {
    // 不可选日期
    disabledDate (date, dateStrings) {
      return date && date.valueOf() > Date.now()
    },
    // 注册时间change
    onChangeregisterTime (dates, dateStrings) {
      if ((dates, dateStrings)) {
        this.queryParam.beginRegisterTime = dateStrings[0]
        this.queryParam.endRegisterTime = dateStrings[1]
      }
    },
    // 最后投递时间change
    onChangelastDeliverTime (dates, dateStrings) {
      if ((dates, dateStrings)) {
        this.queryParam.beginDate = dateStrings[0]
        this.queryParam.endDate = dateStrings[1]
      }
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    // 获取标签数据
    getlableSeleteList () {
      lableSeleteList().then(res => {
        if (res.status == 200) {
          this.lableData = res.data || []
        }
      })
    },
    // 获取首次投递数据
    getStationSeleteList () {
      stationSeleteList().then(res => {
        if (res.status == 200) {
          this.stationData = res.data || []
        }
      })
    },
    // 重置
    refresh () {
      const isONull = this.queryParam.currentGoldMin === null || this.queryParam.currentGoldMin === undefined
      const isOEmpty = this.queryParam.currentGoldMin === ''
      const isOZero = this.queryParam.currentGoldMin === 0
      const isTNull = this.queryParam.currentGoldMax === null || this.queryParam.currentGoldMax === undefined
      const isTEmpty = this.queryParam.currentGoldMax === ''
      const isTZero = this.queryParam.currentGoldMax === 0
      //  第一个为空（可为null可为空字符）第二个不为空
      //  第一个不为空第二个为空（可为null可为空字符）
      //  第一个大于第二个
      if ((isONull || isOEmpty) && (this.queryParam.currentGoldMax || isTZero)) {
        this.$message.error('请输入正确的查询范围！')
        return
      }
      if ((this.queryParam.currentGoldMin || isOZero) && (isTNull || isTEmpty)) {
        this.$message.error('请输入正确的查询范围！')
        return
      }
      if (this.queryParam.currentGoldMin > this.queryParam.currentGoldMax) {
        this.$message.error('请输入正确的查询范围！')
        return
      }
      this.queryParam.currentGoldMin = this.queryParam.currentGoldMin > 999999999 ? 999999999 : this.queryParam.currentGoldMin
      this.queryParam.currentGoldMax = this.queryParam.currentGoldMax > 999999999 ? 999999999 : this.queryParam.currentGoldMax
      this.$refs.table.refresh(true)
    },
    // 查看用户详情
    handleUser (row) {
      this.$router.push({
        path: `/userInfo/userManageList_user/detail/${row.id}`
      })
    },
    // 查看乐豆详情
    handleLd (row) {
      this.$router.push({
        path: '/userInfo/userManageList_Ld/detail',
        query: {
          customerNo: row.customerNo,
          id: row.id
        }
      })
    },
    // 更改启用禁用状态
    changeFlagHandle (text, record) {
      const _this = this
      const _data = {
        id: record.id,
        state: record.state == 1 ? '0' : '1'
      }
      changeStatus(_data).then(res => {
        if (res.status == 200) {
          _this.$message.success(res.message)
          _this.$refs.table.refresh()
        } else {
          record.state = !record.state
        }
      })
    },
    // 重置
    handleReset () {
      this.$refs.queryForm.resetFields()
      this.queryParam.beginDate = null // 最后投递时间的开始时间
      this.queryParam.endDate = null // 最后投递时间的结束时间
      this.queryParam.beginRegisterTime = null //  注册时间最小值
      this.queryParam.endRegisterTime = null //  注册时间最大值
      this.registerTime = []
      this.lastDeliverTime = []
      this.queryParam.labelNoList = []
      this.queryParam.firstDeliveryStationNo = undefined
      this.$refs.table.refresh(true)
    },
    // 导出
    handleExport () {
      const params = this.queryParam
      if (this.registerTime && this.registerTime.length) {
        params.beginRegisterTime = moment(this.registerTime[0]).format('YYYY-MM-DD 00:00:00')
        params.endRegisterTime = moment(this.registerTime[1]).format('YYYY-MM-DD 23:59:59')
      } else {
        params.beginRegisterTime = null
        params.endRegisterTime = null
      }
      if (this.lastDeliverTime && this.lastDeliverTime.length) {
        params.beginDate = moment(this.lastDeliverTime[0]).format('YYYY-MM-DD 00:00:00')
        params.endDate = moment(this.lastDeliverTime[1]).format('YYYY-MM-DD 23:59:59')
      } else {
        params.beginDate = null
        params.endDate = null
      }
      // if (this.lastDeliverTime && this.lastDeliverTime.length) {
      //   params.beginDate = moment(this.lastDeliverTime[0])
      //   params.endDate = moment(this.lastDeliverTime[1])
      //   if (!params.beginDate && !params.endDate) {
      //     this.$message.error('请先选择需要导出的最后投递时间区间再进行导出！')
      //     return
      //   }
      //   // 判断两个时间段是否相差m个月  第二个参数指相差单位，第三个参数指是否返回浮点形式（小数）
      //   if (moment(params.endDate).diff(moment(params.beginDate), 'months', true) > 3) {
      //     this.$message.error('单次最多只能导出3个月的数据，请缩小最后投递时间查询区间后再进行导出！')
      //     return
      //   }
      // } else {
      //   params.beginDate = ''
      //   params.endDate = ''
      // }

      // if (this.registerTime && this.registerTime.length) {
      //   params.beginRegisterTime = moment(this.registerTime[0])
      //   params.endRegisterTime = moment(this.registerTime[1])
      //   if (!params.beginRegisterTime && !params.endRegisterTime) {
      //     this.$message.error('请先选择需要导出的注册时间区间再进行导出！')
      //     return
      //   }
      //   // 判断两个时间段是否相差m个月  第二个参数指相差单位，第三个参数指是否返回浮点形式（小数）
      //   if (moment(params.endRegisterTime).diff(moment(params.beginRegisterTime), 'months', true) > 3) {
      //     this.$message.error('单次最多只能导出3个月的数据，请缩小注册时间查询区间后再进行导出！')
      //     return
      //   }
      // } else {
      //   params.beginRegisterTime = ''
      //   params.endRegisterTime = ''
      // }
      // if (this.lastDeliverTime.length == 0 && this.registerTime.length == 0) {
      //   this.$message.error('请先选择需要导出的注册时间区间或最后投递时间区间再进行导出（3个月以内）！')
      //   return
      // }
	  this.$confirm({
	    title: '提示',
	    content: '导出过程可能需要一段时间，且导出期间不可进行其他操作，确认要导出吗？',
	    onOk: () => {
	  		this.loading = true
	  		customeExport(params).then(res => {
	  		  this.loading = false
	  		  this.download(res)
	  		})
	    },
	    onCancel () {
        }
	  })
    },
    download (data) {
      if (!data) {
        return
      }
      const url = window.URL.createObjectURL(new Blob([data]))
      const link = document.createElement('a')
      link.style.display = 'none'
      link.href = url
      // const a = moment().format('YYYYMMDDhhmmss')
      const fname = '用户列表'
      link.setAttribute('download', fname + '.xlsx')
      document.body.appendChild(link)
      link.click()
    }
  }
}
</script>
<style lang="less" scoped>
	.userManageList-table-page-search-wrapper {
		.userManageList-searchForm {
			.ant-form-inline .ant-form-item {
				width: 100%;
			}

			// 搜索框的下间距
			.ant-form-item {
				margin-bottom: 10px;
			}

			.input-number {
				display: flex;
				margin-top: 3px;
			}

			.handle-btn {
				margin-top: 4px;
			}

			.serach-btn {
				margin-right: 10px;
			}
		}

		.export-btn {
			background-color: #ff9900;
			border-color: #ff9900;
			color: #fff;
			margin-left: 10px;
		}

		.export-btn.ant-btn:focus:not(.ant-btn-primary):not(.ant-btn-danger),
		.export-btn.ant-btn:hover:not(.ant-btn-primary):not(.ant-btn-danger) {
			color: #fff;
			border-color: #ff9900;
		}
	}
</style>
