<template>
  <div v-loading="loading">
    <el-card shadow="hover"
             class="mgb20">
      <div>
        <div class="flex-center mgb20">
          <p class="hr_tag"></p>
          <span>筛选</span>
        </div>
        <div>
          <el-form label-width="80px">
            <el-col :span="4">
              <el-form-item label="省份">
                <el-select v-model="form.provinces"
                           clearable
                           placeholder="请选择省份"
                           @change="getCity"
                           @clear="clearprovince">
                  <el-option v-for="(item,index) in provinceList"
                             :key="index"
                             :label="item.provinceName"
                             :value="item.provinceId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="城市">
                <el-select v-model="form.city"
                           clearable
                           placeholder="请选择城市"
                           :disabled="form.provinces ? false : true"
                           @change="initData">
                  <el-option v-for="(item,index) in cityList"
                             :key="index"
                             :label="item.cityName"
                             :value="item.cityId"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4">
              <el-form-item label="客户类型">
                <el-select v-model="form.customerType"
                           placeholder="请选择客户类型"
                           @change="initData">
                  <el-option v-for="(item,index) in customerTypeList"
                             :key="index"
                             :label="item.name"
                             :value="item.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item>
                <el-input placeholder="支持客户,联系人,账号搜索"
                          prefix-icon="el-icon-search"
                          v-model="form.keyword"
                          clearable></el-input>
              </el-form-item>
            </el-col>
          </el-form>
        </div>
      </div>
    </el-card>

    <el-card shadow="hover"
             class="card">
      <div class="flex-between mgb20">
        <div class="flex-center">
          <p class="hr_tag"></p>
          <span>客户列表</span>
        </div>
        <div>
          <el-button type="primary"
                     round
                     class="mag"
                     @click="exportData">导出客户列表</el-button>
          <el-button type="primary"
                     round
                     class="mag"
                     @click="addcustomer"
                     v-auth>新增</el-button>
          <el-button type="primary"
                     round
                     @click="delAllSelection"
                     v-auth>批量删除</el-button>
        </div>
      </div>
      <el-table :data="listData"
                class="table"
                ref="table"
                stripe
                header-align="center"
                @selection-change="handleSelectionChange"
                row-key="customerId">
        <el-table-column type="selection"
                         width="55"
                         align="center"
                         :reserve-selection="true"></el-table-column>
        <el-table-column type="index"
                         width="100"
                         label="序号"
                         align="center">
          <template slot-scope="scope">
            {{scope.$index + (page - 1) * pageSize + 1}}
          </template>
        </el-table-column>
        <el-table-column prop="customerName"
                         label="客户名称"
                         align="center">
        </el-table-column>
        <el-table-column label="行业"
                         align="center">
          <template slot-scope="scope">
            <span class="ellipsis">{{scope.row.industryName}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="countries"
                         label="客户类型"
                         align="center">
          <template slot-scope="scope">
            <span v-if="scope.row.customerType">{{ customerTypeList.find(e => e.value == scope.row.customerType).name }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="provinceName"
                         label="省份"
                         align="center">
        </el-table-column>
        <el-table-column prop="cityName"
                         label="城市"
                         align="center">
        </el-table-column>
        <el-table-column prop="name"
                         label="联系人"
                         align="center">
        </el-table-column>
        <el-table-column prop="account"
                         label="账号"
                         align="center">
        </el-table-column>
        <el-table-column prop="loginNumber"
                         label="登录次数"
                         align="center">
        </el-table-column>
        <el-table-column label="操作"
                         width="270"
                         align="center">
          <template slot-scope="scope">
            <el-button type="text"
                       @click="resetPassword(scope.row)"
                       v-auth>重置密码</el-button>
            <el-button type="text"
                       @click="show(scope.row)"
                       v-auth>查看</el-button>
            <el-button type="text"
                       @click="edit(scope.row)"
                       v-auth>管理</el-button>
            <el-button type="text"
                       @click="handleDelete(scope.row)"
                       v-auth>删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination background
                       layout="total, prev, pager, next"
                       :total="total"
                       @current-change="handleCurrentChange"
                       :current-page="page">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import Setting from '@/setting'
import axios from 'axios';
import util from "@/libs/util";
export default {
  name: 'customer',
  data () {
    return {
      loading: false,
      searchTimer: null,
      countryList: [{
        name: '中国'
      }],
      customerTypeList: [
        {
          value: '',
          name: '不限'
        },
        {
          name: '正式',
          value: 1
        },
        {
          name: '试用',
          value: 2
        },
        {
          name: '到期',
          value: 3
        }],
      listData: [],
      form: {
        customerType: '',
        provinces: '',
        city: '',
        keyword: ''
      },
      multipleSelection: [],
      provinceList: [],
      cityList: [],
      page: +this.$route.query.page || 1,
      pageSize: 10,
      total: 0,
      ruleIds: []
    };
  },
  watch: {
    'form.keyword': function (val) {
      clearTimeout(this.searchTimer)
      this.searchTimer = setTimeout(() => {
        this.initData()
      }, 500)
    },
  },
  mounted () {
    this.getData()
    this.getProvince()
  },
  methods: {
    getData () {
      const sid = this.$store.state.dataPer.find(e => e.permissionName === '客户管理')
      this.loading = true
      this.$post(this.api.queryCustomer, {
        provinceId: this.form.provinces,
        cityId: this.form.city,
        customerType: this.form.customerType,
        searchContent: this.form.keyword,
        page: this.page,
        size: this.pageSize,
        supplierId: (sid && !sid.all) ? sid.supplierId : ''
      }).then(res => {
        this.listData = res.message.list
        this.total = res.message.totalCount
        this.loading = false
      }).catch(res => {
        this.loading = false
      })
    },
    initData () {
      this.page = 1
      this.getData()
    },
    getProvince () {
      this.$get(this.api.queryProvince).then(res => {
        this.provinceList = res.list
        this.$store.commit("provinceData", { provinceList: this.provinceList })
      }).catch(res => { })
    },
    clearprovince () {
      this.form.city = ''
    },
    getCity () {
      this.clearprovince()
      this.getCityData()
      this.page = 1
      this.initData()
    },
    getCityData () {
      let data = {
        provinceId: this.form.provinces
      }
      this.$get(this.api.queryCity, data).then(res => {
        this.cityList = res.list
      }).catch(res => { })
    },
    permission (row) {
      this.$router.push(`/permission?name=${row.customerName}`)
    },
    // 导出
    async exportData () {
      let sid = this.$store.state.dataPer.find(e => e.permissionName === '客户管理')
      sid = (sid && !sid.all) ? sid.supplierId : ''
      let list = this.multipleSelection
      // 没勾选，则查询所有成绩
      if (!list.length) {
        const res = await this.$post(this.api.queryCustomer, {
          page: 1,
          size: 1000,
          supplierId: sid
        })
        list = res.message.list
      }
      const ids = list.map(e => e.customerId)
      axios.post(this.api.exportClient, {
        exportCustomerIds: ids,
        supplierId: sid
      }, {
        headers: {
          token: this.token
        },
        responseType: 'blob'
      }).then((res) => {
        util.downloadFileDirect(`客户列表.xlsx`, new Blob([res.data]))
      }).catch(res => { })
    },
    addcustomer () {
      this.$router.push('addcustomer')
    },
    edit (row) {
      this.$router.push(`addcustomer?id=${row.customerId}`)
    },
    show (row) {
      this.$router.push(`addcustomer?id=${row.customerId}&show=true`)
    },
    handleDelete (row) {
      this.$confirm('确定要删除吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$post(this.api.delCustomers, [row.customerId]).then(res => {
          this.$message.success('删除成功')
          if (this.listData.length == 2) {

          } else {
            if (this.page > 1) {
              this.page = this.page - 1
            }
          }
          this.getData()
        }).catch(res => { })
      }).catch(() => { })
    },
    handleSelectionChange (val) {
      this.multipleSelection = val
    },
    delAllSelection () {
      if (this.multipleSelection.length != '') {
        let arr = this.multipleSelection
        let delList = arr.map(item => {
          return item.customerId
        })
        this.$confirm('确定要删除吗？', '提示', {
          type: 'warning'
        }).then(() => {
          this.$post(this.api.delCustomers, delList).then(res => {
            this.multipleSelection = [];
            if (delList.length == this.listData.length) {
              if (this.page > 1) {
                this.page = this.page - 1
              }
            }
            this.$refs.table.clearSelection()
            this.$message.success('删除成功')
            this.getData()
          }).catch(res => { })
        }).catch(() => { })
      } else {
        this.$message.error('请先选择数据')
      }
    },
    handleCurrentChange (val) {
      this.page = val
      this.$store.commit('SET_C_PAGE', val)
      this.$router.push(`customer?page=${val}`)
      this.getData()
    },
    resetPassword (row) {
      this.$confirm(`重置后的密码为：${Setting.initialPassword}，确定重置？`, '提示', {
      }).then(() => {
        this.$get(this.api.resetPwdCustomer, {
          customerId: row.customerId,
        }).then(res => {
          if (res.message == 'success') {
            this.$message.success('重置成功')
          } else {
            this.$message.error('重置失败')
          }
        }).catch(res => { });
      }).catch(() => {
      });
    },
  }
};
</script>

<style lang="scss" scoped>
.card {
    min-height: calc(100vh - 300px);
}
</style>

