<template>
  <div class="form-wrap">
    <el-form
      class="search-box"
      ref="form"
      :model="form"
      :inline="true"
      label-width="140px">
      <div class="block-title">
        查询条件
      </div>
      <el-form-item
        label="会员ID"
        prop="filter1">
        <el-input v-model="form.filter1"></el-input>
      </el-form-item>
      <el-form-item
        label="会员类型"
        prop="keyWords1">
        <el-select
          filterable
          v-model="form.keyWords1"
          placeholder="请选择">
          <el-option
            value=""
            label="全部"></el-option>
          <el-option
            v-for="item in memberTypeList"
            :key="item.id"
            :label="item.name"
            :value="item.id">
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="销售起始时间"
        prop="startDate">
        <el-date-picker
          v-model="form.startDate"
          type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="销售截止时间"
        prop="endDate">
        <el-date-picker
          default-time="23:59:59"
          v-model="form.endDate"
          type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="生效查询开始时间"
        prop="startDate1">
        <el-date-picker
          v-model="form.startDate1"
          type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="生效查询结束时间"
        prop="endDate1">
        <el-date-picker
          default-time="23:59:59"
          v-model="form.endDate1"
          type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="截止查询开始时间"
        prop="startDate2">
        <el-date-picker
          v-model="form.startDate2"
          type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="截止查询结束时间"
        prop="endDate2">
        <el-date-picker
          default-time="23:59:59"
          v-model="form.endDate2"
          type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item
        label="姓名"
        prop="keyWords2">
        <el-input v-model="form.keyWords2"></el-input>
      </el-form-item>
      <el-form-item
        label="IC卡号"
        prop="keyWords4">
        <ReaderInput
          type="IC"
          v-model="form.keyWords4">
        </ReaderInput>
      </el-form-item>
      <el-form-item
        label="手机号"
        prop="keyWords3">
        <el-input v-model="form.keyWords3"></el-input>
      </el-form-item>
      <el-form-item
        label="身份证号"
        prop="keyWords5">
        <ReaderInput
          type="ID"
          v-model="form.keyWords5"></ReaderInput>
      </el-form-item>

      <el-form-item
        label="住址"
        prop="keyWords9">
        <el-input v-model="form.keyWords9"></el-input>
      </el-form-item>

      <el-form-item
        label="可用状态"
        prop="keyWords6">
        <el-select v-model="form.keyWords6">
          <el-option
            label="全部"
            value=""
          ></el-option>
          <el-option
            label="可用"
            :value="1"
          ></el-option>
          <el-option
            label="不可用"
            :value="0"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="分销商名称"
        prop="keyWords12"
      >
        <el-select
          v-model="form.keyWords12"
          placeholder="请选择"
        >
          <el-option
            label="全部"
            :value="null"></el-option>
          <el-option
            v-for="(item,index) in saleChannel"
            :key="index"
            :label="item"
            :value="item"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="库存状态"
        prop="keyWords8">
        <el-select v-model="form.keyWords7">
          <el-option
            label="全部"
            value=""
          ></el-option>
          <el-option
            label="已出库"
            :value="1"
          ></el-option>
          <el-option
            label="未出库"
            :value="0"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="激活状态"
        prop="keyWords8">
        <el-select v-model="form.keyWords8">
          <el-option
            label="全部"
            value=""
          ></el-option>
          <el-option
            label="已激活"
            :value="1"
          ></el-option>
          <el-option
            label="未激活"
            :value="0"
          ></el-option>
        </el-select>
      </el-form-item>
      <!-- 【会员客户管理】会员子卡信息(keyWord15)，根据姓名/电话/身份证号查询 -->
      <el-form-item
        label="会员子卡信息"
        prop="keyWords15">
        <el-input
          v-model="form.keyWords15"
          placeholder="根据姓名/电话/身份证号查询"></el-input>
      </el-form-item>
      <el-form-item
        label="人脸图搜索"
        prop="keyWords11">
        <GetFace
          v-model="form.keyWords11"
          skip-check></GetFace>
      </el-form-item>

      <div class="btn-wrap">
        <el-button
          @click="reset">
          重置
        </el-button>
        <el-button
          type="primary"
          @click="getMemberList">
          搜索
        </el-button>
        <el-button
          type="primary"
          @click="exportMemberList">
          导出
        </el-button>
      </div>
    </el-form>

    <div class="table-box">
      <div class="block-title">
        会员卡列表
      </div>
      <el-table
        border
        stripe
        v-loading="loading"
        :data="tableData">
        <el-table-column
          prop="id"
          label="编号">
        </el-table-column>
        <el-table-column
          prop="memberType.name"
          label="会员类型">
        </el-table-column>
        <el-table-column
          width="150"
          prop="otaSourceName"
          label="分销商名称">
        </el-table-column>
        <el-table-column
          prop="name"
          label="姓名">
        </el-table-column>
        <el-table-column
          width="100"
          prop="address"
          label="地址">
          <template slot-scope="prop">
            <Ellipsis
              type="tooltips"
              :content="prop.row.address"
              :length="10"></Ellipsis>
          </template>
        </el-table-column>
        <!-- 狼山定制：搜索使非会员搜不出手机号 （防止demo测试不方便，测试环境还是展示手机号）-->
        <!-- v-if="(searchedwithIDorPhone || (scenicName !== '狼山景区' && scenicName !== 'demo') || checkPermission('member:member_info_update'))" -->
        <el-table-column
          width="100"
          prop="phone"
          v-if="(searchedwithIDorPhone || (scenicName !== '狼山景区') || checkPermission('member:member_info_update'))"
          label="手机号">
        </el-table-column>

        <el-table-column
          width="100"
          prop="remark"
          label="备注">
        </el-table-column>

        <el-table-column
          width="100"
          prop="is_valid"
          label="可用状态">
          <template slot-scope="scope">
            <el-tag
              v-if="scope.row.isActive"
              :type="scope.row.is_valid?'success':'danger'">
              {{ scope.row.is_valid?'有效':'无效' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          width="100"
          prop="isActive"
          label="出库状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.is_out_storage?'success':'info'">
              {{ scope.row.is_out_storage?'已出库':'未出库' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          width="100"
          prop="isActive"
          label="激活状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isActive?'success':'info'">
              {{ scope.row.isActive?'已激活':'未激活' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column
          width="100"
          prop="activate_end_time"
          label="激活截止时间">
          <template slot-scope="scope">
            {{ scope.row.activate_end_time | formatDate }}
          </template>
        </el-table-column>
        <el-table-column
          width="100"
          prop="isUse"
          label="启用状态">
          <template slot-scope="scope">
            <el-tag :type="scope.row.isUse?'success':'info'">
              {{ scope.row.isUse===0?'禁用':'启用' }}
            </el-tag>
          </template>
        </el-table-column>
        <!-- <el-table-column
          label="证件类型">
          <template slot-scope="scope">
            {{ scope.row.papers_type | paperType }}
          </template>
        </el-table-column>
        <el-table-column
          width="160"
          prop="papers_id"
          label="证件号码">
        </el-table-column>
        <el-table-column
          prop="address"
          label="地址">
        </el-table-column> -->
        <el-table-column
          width="150"
          label="创建时间">
          <template slot-scope="prop">
            {{ prop.row.createTime | formatTime }}
          </template>
        </el-table-column>
        <el-table-column
          width="100"
          label="生效时间">
          <template slot-scope="prop">
            {{ prop.row.starttime | formatDate }}
          </template>
        </el-table-column>
        <el-table-column
          width="100"
          label="截止时间">
          <template slot-scope="prop">
            {{ prop.row.endtime | formatDate }}
          </template>
        </el-table-column>
        <el-table-column
          width="150"
          label="无效时间">
          <template slot-scope="prop">
            {{ prop.row.invalid_time }}
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="270"
          fixed="right">
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="showDetail(scope.row)">
              详情
            </el-button>
            <el-button
              type="text"
              size="mini"
              v-if="checkPermission('member:member_edit') && scope.row.is_out_storage &&!scope.row.isActive"
              @click="$refs.delayDialog.show(scope.row.id)">
              激活延期
            </el-button>
            <!-- v-if="(checkPermission('member:member_edit')||checkPermission('member:member_passinfo_edit')) && scope.row.isActive" -->
            <!-- (scenicName !== '狼山景区' && scenicName !== 'demo') -->
            <!-- 狼山定制需求：搜索字段里没有证件号手机号时，只有超级管理员能看到编辑 -->
            <el-button
              type="text"
              size="mini"
              v-if="(((checkPermission('member:member_edit')||checkPermission('member:member_passinfo_edit')) && scope.row.isActive) && (searchedwithIDorPhone || (scenicName !== '狼山景区' && scenicName !== 'demo') || checkPermission('member:member_info_update')))"
              @click="showEditDialog(scope.row)">
              <!-- {{ scenicName }}{{ searchedwithIDorPhone }}{{ (scenicName !== '狼山景区' && scenicName !== 'demo') }} -->
              编辑
            </el-button>
            <el-button
              type="text"
              size="mini"
              v-if="scope.row.memberType.category !==5&&scope.row.memberScenics.length && checkPermission('member:update_checkTimes')"
              @click="$refs.timeEdit.show(scope.row)">
              修改过闸次数
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="switchUse(scope.row)">
              {{ scope.row.isUse===0?'启用':'禁用' }}
            </el-button>

            <el-button
              type="text"
              size="mini"
              :disabled="checkLoading&&scope.row.id===currentId"
              @click="check(scope.row.id)">
              {{ (checkLoading&&scope.row.id===currentId)?'检票中':'检票' }}
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="showModifyHistoryDlg(scope.row)">
              查看修改记录
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        background
        :current-page.sync="form.pageNum"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="form.pageSize"
        @size-change="handleSizeChange"
        @current-change="getMemberList()"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </div>
    <ElDialog
      title="会员详情"
      width="900px"
      v-model="detailDialogVisible">
      <DetailDialog
        :info="currentItem"
      ></DetailDialog>
    </ElDialog>
    <ElDialog
      title="编辑会员卡"
      width="900px"
      v-model="editDialogVisible">
      <DialogEdit
        :com-name="comName"
        :current-type="currentMemberType"
        :current-item="currentItem"
        @updateList="getMemberList"
      ></DialogEdit>
    </ElDialog>
    <ElDialog
      title="查看会员修改历史记录"
      width="900px"
      v-model="modifyHistoryDlgVisible">
      <MemberUpdateLogDlg
        :loading="modifyHistoryDlgLoading"
        :member-update-log-list="memberUpdateLogList"
        @close-member-update-log-dlg="() => this.modifyHistoryDlgVisible = false"
        @send-data="handleFatherSon">
      </MemberUpdateLogDlg>
    </ElDialog>

    <DialogTimeEdit
      ref="timeEdit"
      :member-scenics="currentItem.memberScenics"
      @updateList="getMemberList"
    ></DialogTimeEdit>

    <DelayDialog
      ref="delayDialog"
      @updateList="getMemberList"></DelayDialog>
    <FatherDlg
      ref="fatherDlg">
    </FatherDlg>
    <!-- 狼山定制的编辑前身份证读卡校验  -->
    <!-- 最终把这个身份证设成不可编辑的，就只能读卡器去读 -->
    <ElDialog
      title="身份证读卡校验"
      width="500px"
      v-model="checkIDcardDlgVisible">
      <el-form
        inline
        label-width="140px">
        <div style="width: 100%;display: inline;">
          <div class="block-title">
            与待查记录相匹配的身份证校验
          </div>
          <el-form-item
            label="身份证号">
            <ReaderInput
              type="ID"
              v-model="checkIDcardDlgform.IDcardReaderVal"
              @input="handleIDcardInput_langshan"></ReaderInput>
          </el-form-item>
        </div>
      </el-form>
    </ElDialog>
  </div>
</template>

<script>
import ElDialog from '@/components/Dialog'
import DialogEdit from './memberList/DialogEdit'
import DialogTimeEdit from './memberList/DialogTimeEdit'
import DetailDialog from './memberList/DetailDialog'
import ReaderInput from '@/components/ReaderInput'
import DelayDialog from './memberList/DelayDialog'
import MemberUpdateLogDlg from './memberList/MemberUpdateLogDlg.vue'
import FatherDlg from './memberList/FatherDlg.vue'
import moment from 'moment'
import GetFace from '@/components/GetFace'
import checkPermission from '@/utils/checkPermission'
import { getMemberType, apiMember, exportMemberList, checkMember, getMemberUpdateLogList } from '@/api/member'

export default {
  name: 'memberList',
  components: {
    ElDialog,
    DialogEdit,
    DialogTimeEdit,
    DetailDialog,
    ReaderInput,
    DelayDialog,
    MemberUpdateLogDlg,
    GetFace,
    FatherDlg
  },
  computed: {
    scenicName () {
      return this.$localStore.get('scenicName') || this.$store.state.user.scenicName
    },
    saleChannel () {
      return this.$store.state.app.saleChannel
    }
  },
  data () {
    return {
      comName: '',
      memberTypeList: [],
      searchedwithIDorPhone: false,
      form: {
        startDate: new Date(moment().startOf('day').valueOf()), // 销售起始时间
        endDate: new Date(moment().endOf('day').valueOf()), // 销售截止时间
        startDate1: new Date(moment().startOf('day').valueOf()), // 生效查询开始时间
        endDate1: new Date(moment().endOf('day').valueOf()), // 生效查询结束时间
        startDate2: new Date(moment().startOf('day').valueOf()), // 截止查询开始时间
        endDate2: new Date(moment().endOf('day').valueOf()), // 截止查询结束时间
        filter1: '',
        keyWords1: '', // 会员类型ID
        keyWords2: '', // 姓名
        keyWords3: '', // 手机号
        keyWords4: '', // 卡号
        keyWords5: '', // 身份证号
        keyWords6: '', // 可用状态
        keyWords7: '', // 是否库存
        keyWords8: '', // 激活状态
        keyWords9: '', // 住址
        keyWords11: '',
        keyWords12: null, // 分销商名称
        keyWords15: '', // 会员子卡信息（根据姓名/电话/身份证号查询）
        orderByKeyWords: '',
        orderString: '',
        pageNum: 1,
        pageSize: 10
      },
      checkIDcardDlgform: {
        IDcardReaderVal: '' // 读卡器读到的身份证（狼山定制的编辑前校验）
      },
      tableData: [],
      total: 0,
      detailDialogVisible: false,
      editDialogVisible: false,
      modifyHistoryDlgVisible: false,
      checkIDcardDlgVisible: false, // 狼山定制身份证读卡验证弹窗
      memberUpdateLogList: [], /* /member/getMemberUpdateLogList?memberId= 请求到的会员修改记录 */
      editTimeVisible: false,
      currentItem: {},
      currentMemberType: {},
      currentId: 0,
      modifyHistoryDlgLoading: false, // 会员修改历史记录弹窗的Loading
      checkLoading: false,
      loading: false
    }
  },
  mounted () {
    this.getMemberTypeList().then(() => {
      this.getMemberList()
    })
    // console.log('当前用户的权限们：', this.$route.meta.permissionList)
  },
  methods: {
    checkPermission,
    /**
     * 测试用身份证：342623199604135933 342623199604135511 320623198605264534
     * 读卡器读出来的身份证号：this.checkIDcardDlgform.IDcardReaderVal,
     * 记录中通关的身份证号：this.currentItem.idcard.idcardNo)
     * this.currentItem.papers_id, this.currentItem.idcard.idcardNo 均为身份证号
     * 中华人民共和国居民身份证号码共有18位，其中前6位为地址码，接下来8位为生日码，第17位为性别码，第18位为校验码。
     */
    isReaderIDcardbfEditValid () {
      return (this.checkIDcardDlgform && this.checkIDcardDlgform.IDcardReaderVal && this.checkIDcardDlgform.IDcardReaderVal.length === 18)
    },
    isIDcardMatchEditRecord () {
      // 判断读卡器读出的身份证号码是否与待编辑记录的身份证一致
      // console.log('读卡器读出的身份证：' + this.checkIDcardDlgform.IDcardReaderVal + '，\n该记录的身份证：' + this.currentItem.idcard.idcardNo, '\n是否相符：' + (this.currentItem.idcard.idcardNo === this.checkIDcardDlgform.IDcardReaderVal))
      // 会员信息里的证件号码（身份证号）为this.currentItem.papers_id；通关信息里的身份证号为 this.currentItem.idcard.idcardNo
      let isPass = (this.currentItem.idcard.idcardNo === this.checkIDcardDlgform.IDcardReaderVal) || (this.currentItem.papers_id === this.checkIDcardDlgform.IDcardReaderVal)
      console.log('读卡器读出的身份证：' + this.checkIDcardDlgform.IDcardReaderVal)
      console.log('该记录里的身份证: \n' + ' papers_id->' + this.currentItem.papers_id + ';\n idcard.idcardNo->' + this.currentItem.idcard.idcardNo)
      console.log('是否通过：', isPass)
      return isPass
    },
    handleIDcardInput_langshan () { // 狼山身份证读卡器input事件
      if (!this.isReaderIDcardbfEditValid()) {
        // 身份证不是18位，视为无效，不予处理，防止正确的身份证读取过程中给出不匹配信息
        return
      }
      if (this.isIDcardMatchEditRecord()) {
        this.handleIDcardCheckPassed_langshan(this.currentItem)
      } else {
        this.$message.error('对不起，您的身份证卡号和待编辑的会员记录身份证不符！')
      }
      this.checkIDcardDlgVisible = false
    },
    handleFatherSon (data) {
      // console.log('准备展示:', data)
      this.$refs.fatherDlg.show(data)
    },
    reset () {
      this.$refs.form.resetFields()
    },
    // 获取会员类型
    getMemberTypeList () {
      return getMemberType({
        pageNum: 1,
        pageSize: 999
      }).then(res => {
        this.memberTypeList = res.list
      })
    },
    handleSizeChange (size) {
      this.form.pageSize = size
      this.getMemberList()
    },
    // 获取会员列表
    getMemberList () {
      this.loading = true
      this.searchedwithIDorPhone = false /* 狼山定制 */
      apiMember('getMemberList', this.form).then(res => {
        this.total = res.total
        this.tableData = res.list
      }).finally(() => {
        this.loading = false
        this.searchedwithIDorPhone = this.form.keyWords3.length > 1 || this.form.keyWords5.length > 1 // （狼山定制）搜索时手机号或身份证不为空
      })
    },
    exportMemberList () {
      exportMemberList(this.form).then(res => {
        this.$message.success('导出成功。')
      })
    },
    // 通过身份证校验后，狼山允许查看编辑弹窗
    handleIDcardCheckPassed_langshan (item) {
      let memberType = this.memberTypeList.find(type => type.id === item.memberType.id)
      if (memberType) {
        this.currentMemberType = memberType
        this.currentItem = item
        this.editDialogVisible = true
      } else {
        this.$message.error('会员类型已失效')
      }
    },
    showEditDialog (item) {
      this.checkIDcardDlgform.IDcardReaderVal = '' // 重置狼山身份证
      let memberType = this.memberTypeList.find(type => type.id === item.memberType.id)
      if (memberType) {
        this.currentMemberType = memberType
        this.currentItem = item
        // 狼山管理员有编辑权限，可以跳过身份证弹窗验证
        if (['狼山景区', 'demo'].includes(this.scenicName) && (!checkPermission('member:member_info_update'))) {
        // 狼山定制：编辑之前要身份证读卡器校验，先弹出身份证读卡器弹窗（并且不让普通员工看编辑弹窗）
          this.checkIDcardDlgVisible = true
          return
        }
        this.editDialogVisible = true
      } else {
        this.$message.error('会员类型已失效')
      }
    },
    showModifyHistoryDlg (item) {
      this.modifyHistoryDlgLoading = true
      this.memberUpdateLogList = [] // 置空之前的数据
      // console.log('加载中')
      /**
       * 展示修改记录之前，先要发请求获取展示内容
       * /member/getMemberUpdateLogList  memberId
       */
      getMemberUpdateLogList(item.id).then((res) => {
        this.memberUpdateLogList = res
        /* 不能打印,这个含有图片,打印出来得有几MB console.log(JSON.stringify(this.memberUpdateLogList)) */
        this.modifyHistoryDlgLoading = false
        // console.log('加载完了')
      })
      this.modifyHistoryDlgVisible = true
    },
    showTimeEditDialog (item) {
      this.currentItem = item
      this.editTimeVisible = true
    },
    showDetail (item) {
      this.currentItem = item
      this.detailDialogVisible = true
    },
    switchUse (record) {
      const params = { id: record.id, isUse: record.isUse === 1 ? 0 : 1 }
      apiMember('updateMember', params).then(res => {
        this.$message.success('修改成功')
        this.getMemberList()
      }).catch(err => {
        console.error(err)
      })
    },
    check (id) {
      this.$confirm('确定检票', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.currentId = id
        this.checkLoading = true
        checkMember({ id }).then(res => {
          const { result, errorDetail } = res
          if (result === null) {
            this.$message.success('检票成功')
            this.getMemberList()
          } else {
            this.$message.error(errorDetail)
          }
        }).finally(() => {
          this.checkLoading = false
        })
      }).catch(() => {
      })
    }
  }
}
</script>
<style>
.finger-pic {
  width: 90px;
  height: 120px;
  background-size: contain;
  background-position: center;
}

</style>
