<template>
  <a-card size="small" :bordered="false" class="customerManagementList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div ref="tableSearch" class="table-page-search-wrapper">
        <a-form layout="inline" @keyup.enter.native="$refs.table.refresh(true)">
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-item label="客户名称">
                <a-input id="customerManagementList-customerName" v-model.trim="queryParam.customerName" allowClear placeholder="请输入客户名称"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="联系人">
                <a-input id="customerManagementList-contactName" v-model.trim="queryParam.contactName" allowClear placeholder="请输入联系人"/>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="最后销售时间">
                <rangeDate id="customerManagementList-date" ref="rangeSaleDate" @change="dateSaleChange" />
              </a-form-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-item label="客户关系">
                  <v-select
                    code="CUSTOMER_RELATION_TYPE"
                    id="customerManagementList-relationType"
                    v-model="queryParam.relationType"
                    allowClear
                    placeholder="请选择客户关系"
                  ></v-select>
                </a-form-item>
              </a-col>
              <!--  <a-col :md="6" :sm="24">
                <a-form-item label="是否为下级">
                  <v-select code="FLAG" id="customerManagementList-dealerFlag" v-model="queryParam.dealerFlag" allowClear placeholder="请选择"></v-select>
                </a-form-item>
              </a-col> -->
              <a-col :md="6" :sm="24">
                <a-form-item label="客户地址">
                  <AreaList id="customerManagementList-area" changeOnSelect ref="areaList" @change="areaChange"></AreaList>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="客户类型">
                  <custType id="customerManagementList-custType" v-model="queryParam.customerTypeSn" allowClear placeholder="请选择客户类型"></custType>
                </a-form-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="启用状态">
                  <v-select id="customerManagementList-flag" code="ENABLE_FLAG" v-model="queryParam.enabledFlag" allowClear placeholder="请选择启用状态"></v-select>
                </a-form-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
              <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="customerManagementList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="customerManagementList-reset">重置</a-button>
              <a @click="advanced=!advanced" style="margin-left: 5px" id="customerManagementList-advanced">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </a-col>
          </a-row>
        </a-form>
      </div>
      <!-- 操作按钮 -->
      <div class="table-operator">
        <a-button v-if="$hasPermissions('B_customer_customerInfo_add')" id="customerManagementList-add" type="primary" class="button-error" @click="handleEdit()">新增</a-button>
      </div>
      <!-- 列表 -->
      <s-table
        class="sTable fixPagination"
        ref="table"
        :style="{ height: tableHeight+68+'px' }"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ y: tableHeight }"
        :defaultLoadData="false"
        bordered>
        <!-- 操作 -->
        <template slot="action" slot-scope="text, record">
          <a-button
            size="small"
            v-if="$hasPermissions('B_customer_customerInfo_edit')"
            type="link"
            class="button-primary"
            @click="handleEdit(record)"
            :id="'customerManagementList-edit-'+record.id">编辑</a-button>
          <a-button
            size="small"
            v-if="$hasPermissions('B_customer_customerInfo_detail')"
            type="link"
            class="button-success"
            @click="handleDetail(record)"
            :id="'customerManagementList-detail-'+record.id">详情</a-button>
          <a-button
            size="small"
            v-if="$hasPermissions('B_customer_customerInfo_edit')"
            type="link"
            class="button-primary"
            @click="mergeCustomer(record)"
            :id="'customerManagementList-merge-'+record.id">合并</a-button>
          <span v-if="!$hasPermissions('B_customer_customerInfo_edit') && !$hasPermissions('B_customer_customerInfo_detail')">--</span>
        </template>
        <template slot="enableAction" slot-scope="text, record">
          <a-switch
            :id="'customerManagementList-switch-'+record.id"
            v-if="$hasPermissions('B_customer_customerInfo_enable')"
            checkedChildren="启用"
            unCheckedChildren="禁用"
            v-model="record.enabledFlag"
            @change="changeFlagHandle(text, record)"/>
          <span v-else :style="{color:(record.enabledFlag==1?'#00aa00':'#999')}"> {{ record.enabledFlag==1? '已启用': '已禁用' }} </span>
        </template>
      </s-table>
    </a-spin>
    <!-- 客户详情 -->
    <customer-management-detail-modal :openModal="openModal" :itemId="itemId" @close="closeModal" />
    <!-- 合并用户 -->
    <merge-customer-modal :openModal="openMergeModal" :params="customerTemp" @close="closeMergeModal" />
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { custList, custDel, updateEnableStatus } from '@/api/customer'
import AreaList from '@/views/common/areaList.js'
import custType from '@/views/common/custType.js'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import customerManagementDetailModal from './detailModal.vue'
import mergeCustomerModal from './mergeCustomerModal.vue'
export default {
  name: 'CustomerManagementList',
  components: { STable, VSelect, customerManagementDetailModal, rangeDate, AreaList, custType, mergeCustomerModal },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0,
      queryParam: { //  查询条件
        saleBeginDate: '',
        saleEndDate: '',
        customerName: undefined, //  客户名称
        contactName: '', //  联系人
        provinceSn: undefined, //  省
        citySn: undefined, //  市
        countySn: undefined, //  区
        dealerFlag: undefined, //  是否卫星仓客户
        customerTypeSn: undefined, //  客户类型
        enabledFlag: '1', //  启用状态
        relationType: undefined // 客户关系
      },
      disabled: false, //  查询、重置按钮是否可操作
      columns: [
        { title: '序号', dataIndex: 'no', width: '4%', align: 'center' },
        { title: '客户名称', dataIndex: 'customerName', width: '28%', align: 'left', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '联系人', dataIndex: 'contactName', width: '7%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '联系电话', dataIndex: 'contactTel', width: '9%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '联系手机', dataIndex: 'contactMobile', width: '9%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '创建时间', dataIndex: 'createDate', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '最后销售时间', dataIndex: 'lastSaleTime', width: '11%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户关系', dataIndex: 'relationTypeDictValue', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        // { title: '是否为下级', dataIndex: 'dealerFlagDictValue', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '价格类型', dataIndex: 'priceTypeDictValue', width: '7%', align: 'center', customRender: function (text) { return text || '--' } },
        { title: '启用状态', scopedSlots: { customRender: 'enableAction' }, width: '8%', align: 'center' },
        { title: <div><a-tooltip placement='top' title='注意：客户合并功能中，将以当前客户为对象，合并被选客户。'><a-icon type="question-circle" /></a-tooltip>&nbsp;操作</div>, scopedSlots: { customRender: 'action' }, width: '10%', align: 'center' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        this.spinning = true
        return custList(Object.assign(parameter, this.queryParam)).then(res => {
          let data
          if (res.status == 200) {
            data = res.data
            const no = (data.pageNo - 1) * data.pageSize
            for (var i = 0; i < data.list.length; i++) {
              data.list[i].no = no + i + 1
              data.list[i].enabledFlag = data.list[i].enabledFlag + '' === '1'
            }
            this.disabled = false
          }
          this.spinning = false
          return data
        })
      },
      addrProvinceList: [], //  省下拉
      addrCityList: [], //  市下拉
      addrDistrictList: [], //  区下拉
      openModal: false, //  查看客户详情  弹框
      itemId: '', //  当前客户id
      openMergeModal: false, // 合并用户名称
      customerTemp: {}// 临时客户数据
    }
  },
  methods: {
    //  时间  change
    dateSaleChange (date) {
      this.queryParam.saleBeginDate = date[0] ? date[0] : ''
      this.queryParam.saleEndDate = date[1] ? date[1] : ''
    },
    // 地区
    areaChange (val) {
      this.queryParam.provinceSn = val[0] ? val[0] : undefined
      this.queryParam.citySn = val[1] ? val[1] : undefined
      this.queryParam.countySn = val[2] ? val[2] : undefined
    },
    //  重置
    resetSearchForm () {
      this.$refs.rangeSaleDate.resetDate()
      this.queryParam.saleBeginDate = ''
      this.queryParam.saleEndDate = ''
      this.queryParam.customerName = undefined
      this.queryParam.contactName = ''
      this.queryParam.provinceSn = undefined
      this.queryParam.citySn = undefined
      this.queryParam.countySn = undefined
      this.queryParam.dealerFlag = undefined
      this.queryParam.customerTypeSn = undefined
      this.queryParam.relationType = undefined
      this.queryParam.enabledFlag = '1'
      this.addrCityList = []
      this.addrDistrictList = []
      if (this.advanced) {
        this.$refs.areaList.clearData()
      }
      this.$refs.table.refresh(true)
    },
    //  新增/编辑
    handleEdit (row) {
      if (row) { //  编辑
        this.$router.push({ path: `/customerManagement/customerInfo/edit/${row.id}` })
      } else { //  新增
        this.$router.push({ path: '/customerManagement/customerInfo/add' })
      }
    },
    //  删除
    handleDel (row) {
      const _this = this
      this.$confirm({
        title: '提示',
        content: '删除后不可恢复，确定要进行删除吗？',
        centered: true,
        onOk () {
          _this.spinning = true
          custDel({ id: row.id }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
              _this.spinning = false
            } else {
              _this.spinning = false
            }
          })
        }
      })
    },
    // 修改状态
    changeFlagHandle (text, record) {
      const _data = {
        id: record.id,
        flag: record.enabledFlag ? '1' : '0'
      }
      this.spinning = true
      updateEnableStatus(_data).then(res => {
        if (res.status == 200) {
          this.$message.success(res.message)
          this.$refs.table.refresh()
          this.spinning = false
        } else {
          this.$refs.table.refresh()
          this.spinning = false
        }
      })
    },
    //  客户信息详情
    handleDetail (row) {
      this.itemId = row.id
      this.openModal = true
    },
    // 合并客户
    mergeCustomer (row) {
      this.customerTemp = row
      this.openMergeModal = true
    },
    // 关闭合并客户弹框
    closeMergeModal (flag) {
      this.customerTemp = ''
      this.openMergeModal = false
      if (flag) {
        this.$refs.table.refresh()
      }
    },
    //  关闭弹框
    closeModal () {
      this.itemId = ''
      this.openModal = false
    },
    pageInit () {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    setTableH () {
      const tableSearchH = this.$refs.tableSearch.offsetHeight
      this.tableHeight = window.innerHeight - tableSearchH - 220
    }
  },
  watch: {
    advanced (newValue, oldValue) {
      const _this = this
      this.$nextTick(() => { // 页面渲染完成后的回调
        _this.setTableH()
      })
    },
    '$store.state.app.winHeight' (newValue, oldValue) { //  窗口变更时，需同时更改表格高度
      this.setTableH()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
    // 仅刷新列表，不重置页面
    if (this.$store.state.app.updateList) {
      this.pageInit()
      this.$refs.table.refresh()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
