<template>
  <div class="user-info-container">
    <vab-query-form>
      <vab-query-form-left-panel :span="4">
        <el-button icon="el-icon-plus" type="primary" @click="handleEdit">
          {{ __('添加') }}
        </el-button>
        <el-button icon="el-icon-printer" type="primary" @click="exportCsv">
          {{ __('导出') }}
        </el-button>
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="20">
        <el-form
          :inline="true"
          label-width="50px"
          :model="queryForm"
          @submit.native.prevent
        >
          <el-form-item>
            <el-select
              v-if="false"
              v-model="queryForm.user_certification"
              clearable
              :placeholder="__('请选择认证状态')"
            >
              <el-option
                v-for="item in certificationOptions"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
            <el-radio-group v-model="queryForm.user_certification" @change="queryData">
              <el-radio-button v-for="item in certificationOptions" :key="item.value" :label="item.value" >{{item.label}}</el-radio-button>
            </el-radio-group>
          </el-form-item>

          <el-form-item>
            <el-select
              v-model.trim="queryForm.user_level_id"
              clearable
              :placeholder="__('用户等级')"
              style="width: 100px"
            >
              <el-option
                v-for="item in levelOptions"
                :key="item.user_level_id"
                :label="item.user_level_name"
                :value="item.user_level_id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model.trim="queryForm.user_state"
              clearable
              :placeholder="__('账号状态')"
              style="width: 100px"
            >
              <el-option
                v-for="item in stateOptions"
                :key="item.value"
                :disabled="item.disabled"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input
              v-model.trim="queryForm.user_account"
              clearable
              :placeholder="__('用户账号')"
              style="width: 120px"
            />
          </el-form-item>
          <el-form-item>
            <el-input
              v-model.trim="queryForm.user_nickname"
              clearable
              :placeholder="__('用户昵称')"
              style="width: 120px"
            />
          </el-form-item>
          <el-form-item>
            <el-input
              v-model.trim="queryForm.user_mobile"
              clearable
              :placeholder="__('用户手机号')"
              style="width: 120px"
            />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="queryData">
              {{ __('查询') }}
            </el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table
      v-loading="listLoading"
      border
      :data="list"
      :height="tableConfig.height"
    >
      <el-table-column
        align="center"
        fixed="left"
        :label="__('操作')"
        width="120"
      >
        <template #default="{ row }">
          <el-button type="text" @click="handleEdit(row)">
            {{ __('编辑') }}
          </el-button>
          <el-button type="text" @click="handleDelete(row)">
            {{ __('删除') }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        fixed="left"
        :label="__('用户编号')"
        prop="user_id"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('用户账号')"
        prop="user_account"
        show-overflow-tooltip
        width="160"
      />
      <el-table-column
        align="center"
        :label="__('用户昵称')"
        prop="user_nickname"
        show-overflow-tooltip
        width="120"
      />
      <el-table-column
        v-if="false"
        align="center"
        :label="__('备注名称')"
        prop="user_notename"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('来源编号')"
        prop="user_parent_id"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('状态')"
        prop="user_state"
        show-overflow-tooltip
        width="120"
      >
        <template slot-scope="scope">
          <el-select
            v-model="scope.row.user_state"
            :placeholder="__('用户账号状态')"
            @change="(val) => changeState(val, scope)"
          >
            <el-option
              v-for="item in stateOptions"
              :key="item.value"
              :disabled="item.disabled"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="__('用户等级')"
        prop="user_level_name"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('头像')"
        prop="user_avatar"
        show-overflow-tooltip
      >
        <template slot-scope="scope">
          <el-popover placement="top-start" title="" trigger="hover">
            <img
              v-if="scope.row.user_avatar"
              alt=""
              :src="scope.row.user_avatar"
              style="width: 150px; height: 150px"
            />
            <img
              v-if="scope.row.user_avatar"
              slot="reference"
              :src="scope.row.user_avatar"
              style="width: 30px; height: 30px"
            />
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :formatter="formatGender"
        :label="__('性别')"
        prop="user_gender"
        show-overflow-tooltip
      >
        <template #default="{ row }">
          <el-tag :type='({"0":"info","1":"success","2":"waring"})[row.user_gender]'>
            {{ ({"0":"未知","1":"男","2":"女"})[row.user_gender] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="__('真实姓名')"
        prop="user_realname"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('身份证')"
        prop="user_idcard"
        show-overflow-tooltip
        width="180"
      />
      <el-table-column
        align="center"
        :label="__('身份证图片')"
        prop="user_idcard_images"
        show-overflow-tooltip
        width="140"
      >
        <template slot-scope="scope">
          <el-image
            v-for="(user_idcard_image, index) in scope.row.user_idcard_images"
            :key="index"
            :preview-src-list="
              getPreviewImgList(index, scope.row.user_idcard_images)
            "
            :src="user_idcard_image"
            style="width: 35px; height: 35px"
          />
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="__('实名认证')"
        prop="user_certification"
        show-overflow-tooltip
        width="100"
      >
        <template #default="{ row }">
          <el-button
            v-if="row.user_certification === 1"
            type="primary"
            @click="editCertification(row, 0)"
          >
            {{ __('已认证') }}
          </el-button>
          <el-button
            v-else-if="row.user_certification === 2"
            type="info"
            @click="editCertification(row, 1)"
          >
            {{ __('待审核') }}
          </el-button>
          <div v-else>
            {{ __('未验证') }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="__('社交认证')"
        prop="user_certified_sns"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('认证类型')"
        prop="user_type_name"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :formatter="formatbirthday"
        :label="__('生日')"
        prop="user_birthday"
        show-overflow-tooltip
        width="160"
      />
      <el-table-column
        align="center"
        :label="__('手机号码')"
        prop="user_mobile"
        show-overflow-tooltip
        width="120"
      />
      <el-table-column
        align="center"
        :label="__('电话')"
        prop="user_tel"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('用户邮箱')"
        prop="user_email"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('QQ')"
        prop="user_qq"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('阿里旺旺')"
        prop="user_ww"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('省')"
        prop="user_province_id"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('省')"
        prop="user_province_name"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('城市')"
        prop="user_city_id"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('城市')"
        prop="user_city_name"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('县')"
        prop="user_county_id"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('县')"
        prop="user_county_name"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('详细地址')"
        prop="user_address"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('签名')"
        prop="user_sign"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :formatter="formatTime"
        :label="__('注册时间')"
        prop="user_reg_datetime"
        show-overflow-tooltip
        width="160"
      />
      <el-table-column
        align="center"
        :label="__('注册IP')"
        prop="user_reg_ip"
        show-overflow-tooltip
        width="140"
      />
      <el-table-column
        align="center"
        :formatter="formatLogTime"
        :label="__('登录时间')"
        prop="user_lastlogin_time"
        show-overflow-tooltip
        width="160"
      />
      <el-table-column
        align="center"
        :label="__('登录IP')"
        prop="user_lastlogin_ip"
        show-overflow-tooltip
        width="140"
      />
      <el-table-column
        align="center"
        :formatter="formatAdmin"
        :label="__('是否管理员')"
        prop="user_is_admin"
        show-overflow-tooltip
        width="100"
      >
        <template #default="{ row }">
          <el-tag :type='({"0":"info","1":"success","2":"waring"})[row.user_is_admin]'>
            {{ ({"0":"否","1":"是","2":"是"})[row.user_is_admin] }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column
        align="center"
        :label="__('店铺账号')"
        prop="store_ids"
        show-overflow-tooltip
      />
      <el-table-column
        align="center"
        :label="__('门店账号')"
        prop="chain_ids"
        show-overflow-tooltip
      />
    </el-table>
    <el-pagination
      background
      :current-page="queryForm.pageNum"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange"
    />
    <edit ref="edit" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import { translateTitle as __ } from '@/utils/i18n'
  import { doDelete, doEdit, getList } from '@/api/user/account'
  import Edit from './components/UserAccountEdit'
  import { renderTime, timeToYMD } from '@/utils/date'
  import { editCertification, exportFile } from '@/api/user/info'
  import {getList as listUserLevel} from "@/api/base/user/level";

  export default {
    name: 'UserBase',
    components: { Edit },
    data() {
      return {
        tableConfig: {
          height: window.innerHeight - 220 - 90,
        },
        list: [],
        listLoading: true,
        layout: 'total, sizes, prev, pager, next, jumper',
        total: 0,
        selectRows: '',
        queryForm: {
          pageNum: 1,
          pageSize: 20,
          user_certification: null,
          is_admin: '',
        },
        stateOptions: [
          {
            value: 0,
            label: this.__('锁定'),
          },
          {
            value: 1,
            label: this.__('未激活'),
          },
          {
            value: 2,
            label: this.__('已激活'),
          },
        ],
        certificationOptions: [
          {
            value: null,
            label: this.__('全部'),
          },
          {
            value: 0,
            label: this.__('未认证'),
          },
          {
            value: 1,
            label: this.__('已认证'),
          },
          {
            value: 2,
            label: this.__('待审核'),
          },
        ],
        levelOptions:[],
      }
    },
    created() {
      let query = this.$route.query
      if (query.user_certification) {
        this.queryForm.user_certification = Number(query.user_certification)
      }
      this.queryData()
      this.getUserLevelList()
    },
    methods: {
      getPreviewImgList: function (index, user_idcard_images) {
        let result = []
        for (let i = 0; i < user_idcard_images.length; i++) {
          result.push(user_idcard_images[i + index])
          if (i + index >= user_idcard_images.length - 1) {
            // 为了取后边小值（采用绝对值）
            index = 0 - (i + 1)
          }
        }
        return result
      },
      changeState(val, scope) {
        let row = scope.row
        this.$baseConfirm(
          this.__('请确认是否更改状态？'),
          null,
          async () => {
            const { msg, status } = await doEdit(row)
            if (200 == status) {
              this.$baseMessage(msg, 'success')
            } else {
              this.$baseMessage(msg, 'error')
            }
            await this.fetchData()
          },
          async () => {
            await this.fetchData()
          }
        )
      },
      formatAdmin(row) {
        return row.user_is_admin === 1 ? this.__('是') : this.__('否')
      },
      formatGender(row) {
        if (row.user_gender === 0) {
          return this.__('未知')
        } else {
          return row.user_gender === 1 ? this.__('男') : this.__('女')
        }
      },
      __,
      formatbirthday(row) {
        const user_birthday = row.user_birthday
        return user_birthday ? timeToYMD(user_birthday) : ''
      },
      formatLogTime(row) {
        const user_lastlogin_time = row.user_lastlogin_time
        return user_lastlogin_time ? renderTime(user_lastlogin_time) : ''
      },
      formatTime(row) {
        const user_reg_datetime = row.user_reg_datetime
        return user_reg_datetime ? renderTime(user_reg_datetime) : ''
      },
      handleEdit(row) {
        if (row.user_id) {
          this.$refs['edit'].showEdit(row)
        } else {
          this.$refs['edit'].showEdit()
        }
      },
      handleDelete(row) {
        if (row.store_ids != '' && row.store_ids.length > 0) {
          this.$baseAlert('该用户为店铺账户，不能删除！')
          return
        }
        if (row.user_id) {
          this.$baseConfirm(this.__('你确定要删除当前项吗'), null, async () => {
            const { msg, status } = await doDelete({ user_ids: row.user_id })
            if (200 == status) {
              this.$baseMessage(msg, 'success')
            } else {
              this.$baseMessage(msg, 'error')
            }
            await this.fetchData()
          })
        }
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.fetchData()
      },
      queryData() {
        this.queryForm.pageNum = 1
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        const { data } = await getList(this.queryForm)
        this.list = data.items
        console.log(this.list)
        this.total = data.records
        this.listLoading = false
      },
      exportCsv() {
        exportFile(this.queryForm).then((data) => {
          const blob = new Blob([data])
          const downloadElement = document.createElement('a')
          const href = window.URL.createObjectURL(blob) //创建下载的链接
          downloadElement.href = href
          downloadElement.download = decodeURIComponent('用户数据.csv') //下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() //点击下载
          document.body.removeChild(downloadElement) //下载完成移除元素
          window.URL.revokeObjectURL(href) //释放掉blob对象
        })
      },
      async editCertification(row, user_certification) {
        let user_id = row.user_id
        const { msg, status } = await editCertification({
          user_id: user_id,
          user_certification: user_certification,
        })
        if (200 == status) {
          this.$baseMessage(msg, 'success')
        } else {
          this.$baseMessage(msg, 'error')
        }
        await this.fetchData()
      },

      async getUserLevelList() {
        let param = {
          pageNum: 1,
          pageSize: 9999,
        }
        const { data } = await listUserLevel(param)
        if (data) {
          this.levelOptions = data.items
        } else {
          this.levelOptions = []
        }
      },
    },
  }
</script>
