<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="客户姓名"
        prop="keyWords1">
        <el-input v-model="form.keyWords1"></el-input>
      </el-form-item>

      <el-form-item
        label="身份证号"
        prop="keyWords2">
        <ReaderInput
          type="ID"
          v-model="form.keyWords2"></ReaderInput>
      </el-form-item>

      <el-form-item
        label="区域"
        prop="region">
        <el-cascader
          v-model="form.region"
          :options="regionOptions"
          :props="cascaderProps"
          :show-all-levels="false"
          @change="regionChange"
        ></el-cascader>
      </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="2"
          ></el-option>
        </el-select>
      </el-form-item>

      <el-form-item
        label="客户状态"
        prop="keyWords6">
        <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-option
            label="灰名单"
            :value="3"
          ></el-option>
        </el-select>
      </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="area"
      >
        <el-cascader
          :disabled="!areaOptions.length"
          v-model="form.area"
          :options="areaOptions"
          :props="cascaderProps"
          :show-all-levels="false"
          @change="areaChange"
        ></el-cascader>
      </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="keyWords8"
      >
        <el-input v-model.number="form.keyWords8">
        </el-input>
      </el-form-item> -->
      <!-- <el-form-item
        label="最大检票次数"
        prop="keyWords9"
      >
        <el-input v-model.number="form.keyWords9">
        </el-input>
      </el-form-item> -->

      <div class="btn-wrap">
        <el-button
          @click="reset"
        >
          重置
        </el-button>
        <el-button
          type="primary"
          @click="getList"
        >
          查询
        </el-button>

        <el-button
          type="primary"
          @click="reportExport">
          导出
        </el-button>

        <el-button
          type="primary"
          @click="showDialog('new')"
        >
          新增客户
        </el-button>
      </div>
    </el-form>
    <div class="table-box">
      <div style="position:relative">
        <div style="position: absolute; top:-8px;right:0;width:170px;display: flex;">
          <el-button
            @click="downloadTemp"
            style="margin-right:10px">
            下载模板
          </el-button>
          <el-upload
            :action="uploadUrl"
            :auto-upload="true"
            :show-file-list="false"
            :on-success="handleSuccess"
            :on-error="handleError"
          >
            <el-button type="primary">
              导入模板
            </el-button>
          </el-upload>
        </div>
      </div>

      <div class="block-title">
        查询信息
      </div>
      <el-table
        v-loading="loading"
        stripe
        border
        :data="tableData">
        <el-table-column
          prop="name"
          label="客户姓名"
        >
        </el-table-column>
        <el-table-column
          prop="region"
          label="区域"
        >
        </el-table-column>
        <el-table-column
          prop="area"
          label="地区"
        >
        </el-table-column>
        <el-table-column
          label="证件类型"
        >
          <template slot-scope="scope">
            {{ scope.row.papers_type | paperType }}
          </template>
        </el-table-column>
        <el-table-column
          v-if="projectName === 'czg'"
          width="170"
          prop="sensitive_papers_id"
          label="证件号"
        >
        </el-table-column>
        <el-table-column
          v-else
          width="170"
          prop="papers_id"
          label="证件号"
        >
          <!--
          <template slot-scope="scope">
            <span v-if="hide">{{ scope.row.sensitive_papers_id }}</span>
            <span v-if="!hide">{{ scope.row.papers_id }}</span>
          </template>
           -->
          <template slot-scope="scope">
            {{ isPapersIdDesensitize ? $options.filters.formatIDCard(scope.row.papers_id) : scope.row.papers_id }}
          </template>
        </el-table-column>
        <el-table-column
          width="120"
          prop="phone"
          label="手机号"
        >
        </el-table-column>
        <el-table-column
          label="客户类型"
        >
          <template slot-scope="scope">
            {{ scope.row.type | customerType }}
          </template>
        </el-table-column>

        <el-table-column
          label="创建时间"
        >
          <template slot-scope="scope">
            {{ scope.row.createTime | formatTime }}
          </template>
        </el-table-column>

        <el-table-column
          label="状态"
        >
          <template slot-scope="scope">
            <el-tag
              :type="scope.row.status===1?'success':scope.row.status===0?'info':'primary'"
            >
              {{ scope.row.status | customerStatus }}
            </el-tag>
          </template>
        </el-table-column>

        <el-table-column
          width="180"
          label="操作"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="mini"
              @click="showDialog('edit', scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="text"
              size="mini"
              @click="delRow(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="getList()"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </div>

    <ElDialog
      :title="dialogType==='new'?'新增客户':'编辑客户'"
      width="740px"
      v-model="dialogVisible"
    >
      <DialogNew
        :dialog-type="dialogType"
        :current-item="currentItem"
        @updateList="getList"
      ></DialogNew>
    </ElDialog>
  </div>
</template>

<script>
import { apiVisitor, exportCustomerList } from '@/api/visitor'
/*
import { getSystemConfigList } from '@/api/systemConfig'
*/
import ElDialog from '@/components/Dialog'
import DialogNew from './visitorManage/DialogNew'
import regionData from '@/assets/region.json'
import areaData from '@/assets/area.json'
import ReaderInput from '@/components/ReaderInput'
import moment from 'moment'

export default {
  components: {
    ElDialog,
    DialogNew,
    ReaderInput
  },
  data () {
    return {
      projectName: process.env.VUE_APP_PROJECT,
      loading: false,
      total: 0,
      tableData: [],
      dialogVisible: false,
      dialogType: 'new',
      currentItem: {},
      regionOptions: [{ name: '全部', value: '' }, ...regionData],
      areaOptions: [],
      cascaderProps: {
        label: 'name',
        value: 'value',
        children: 'children'
      },
      form: {
        keyWords1: '', // 姓名
        keyWords2: '', // 证件号
        keyWords3: '', // 手机号
        keyWords4: '', // 区域
        keyWords5: '', // 城市地区
        keyWords6: '', // 类型
        keyWords7: '', // 客户状态
        // keyWords8: '',
        // keyWords9: '',
        region: [''],
        area: [''],
        pageNum: 1,
        pageSize: 10,
        startDate: new Date(moment().startOf('day').valueOf()),
        endDate: new Date(moment().endOf('day').valueOf())
      },
      /*
      hide: false,
      */
      chineseRegion: ['华北', '东北', '华东', '中南', '西南', '西北'],
      uploadUrl: ''
    }
  },
  async mounted () {
    this.getList()
    /*
    const res = await getSystemConfigList()
    const customer_papers_id_desensitize = res.list.find(v => v.configKey === 'customer_papers_id_desensitize')?.configValue
    if (customer_papers_id_desensitize === '1') {
      this.hide = true
    }
    */
  },
  computed: {
    isPapersIdDesensitize () {
      const value = this.$store.state.app.systemConfig.find(i => i.configKey === 'papers_id_desensitize')?.configValue
      return value === '1'
    }
  },
  filters: {
    customerType (input) {
      switch (input) {
        case 1:
          return '普通'
        default:
          return '其他'
      }
    },
    customerStatus (input) {
      switch (input) {
        case 0:
          return '黑名单'
        case 1:
          return '正常'
        case 3:
          return '灰名单'
        default:
          return '其他'
      }
    }
  },
  methods: {
    handleSizeChange (size) {
      this.form.pageSize = size
      this.getList()
    },
    // 获取列表
    getList () {
      this.loading = true
      apiVisitor('getCustomerList', this.form).then(res => {
        this.total = res.total
        this.tableData = res.list
        if (this.projectName === 'czg') {
          this.tableData.forEach(v => {
            if (v.phone.length === 11) {
              v.phone = v.phone.substring(0, 3) + '******' + v.phone.substring(9)
            }
          })
        }
      }).finally(() => {
        this.loading = false
      })
    },
    reset () {
      this.$refs.form.resetFields()
      this.form.keyWords4 = ''
      this.form.keyWords5 = ''
      this.areaOptions = []
    },
    // 改变区域选择器
    regionChange (arr) {
      let val = arr[arr.length - 1]
      this.form.keyWords4 = val
      let provinceData = areaData[val]
      if (provinceData) {
        this.areaOptions = [
          {
            name: '全部',
            value: ''
          },
          ...provinceData
        ]
      } else {
        this.areaOptions = []
      }
      this.$nextTick(() => {
        this.form.area = ['']
        this.form.keyWords5 = ''
      })
    },
    // 改变城市选择器
    areaChange (arr) {
      let val = arr[arr.length - 1]
      this.form.keyWords5 = val
    },
    showDialog (type, item) {
      this.dialogType = type
      this.currentItem = item
      this.dialogVisible = true
    },
    delRow (row) {
      this.$confirm('确认删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        apiVisitor('deleteCustomer', row).then(() => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getList()
        })
      })
    },
    downloadTemp () {
      window.location.href = require('path').join(__static, '客户导入模板.xlsx')
    },
    handleSuccess (response, file, fileList) {
      if (response.resCode === 200) {
        this.$message.success('上传成功')
        this.getList()
      } else {
        this.$message.error('上传失败')
      }
    },
    handleError (e) {
      this.$message.error('上传失败')
    },
    reportExport () {
      exportCustomerList(this.form).then(() => {
        this.$message.success('导出成功。')

        this.goToDownload()
      }, () => {
        this.$message.success('导出失败。')
      })
    }
  },
  created () {
    const Store = require('electron-store')
    const localStore = new Store()
    this.uploadUrl = localStore.get('serverUrl') + '/customer/importCustomer'
  }
}
</script>

<style scoped lang="scss">
  .info-form {
    display: flex;
    flex-wrap: wrap;
    .info-form-item {
      width: 33%;
      display: flex;
      align-items: center;
      .info-form-label {
        flex-shrink: 0;
        width: 70px;
        padding-right: 12px;
        color: #64667B;
      }
    }
  }
</style>
