<template>
  <a-card size="small" :bordered="false" class="customerManagementList-wrap">
    <!-- 搜索条件 -->
    <div 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-range-picker
                style="width:100%"
                allowClear
                id="customerManagementList-creatTime"
                :disabledDate="disabledDate"
                v-model="creatTime"
                :format="dateFormat"
                :placeholder="['开始时间', '结束时间']" />
            </a-form-item>
            </a-form-item>
          </a-col>
          <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>
          <template v-if="advanced">
            <a-col :md="6" :sm="24">
              <a-form-item label="最后销售时间">
                <a-range-picker
                  style="width:100%"
                  allowClear
                  id="customerManagementList-lastSaleTime"
                  :disabledDate="disabledDate"
                  v-model="lastSaleTime"
                  :format="dateFormat"
                  :placeholder="['开始时间', '结束时间']" />
              </a-form-item>
              </a-form-item>
            </a-col>
            <a-col :md="12" :sm="24">
              <a-row>
                <!-- 客户地址 -->
                <a-form-item label="客户地址">
                  <a-col span="7">
                    <a-form-item prop="provinceSn" style="margin: 0;">
                      <a-select v-model="queryParam.provinceSn" @change="getCityList" placeholder="请选择省">
                        <a-select-option v-for="item in addrProvinceList" :value="item.id" :key="item.id + 'a'">{{ item.name }}</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col span="7" offset="1">
                    <a-form-item prop="citySn" style="margin: 0;">
                      <a-select v-model="queryParam.citySn" @change="getAreaList" placeholder="请选择市">
                        <a-select-option v-for="item in addrCityList" :value="item.id" :key="item.id + 'b'">{{ item.name }}</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                  <a-col span="7" offset="1">
                    <a-form-item prop="countySn" style="margin: 0;">
                      <a-select v-model="queryParam.countySn" placeholder="请选择区/县">
                        <a-select-option v-for="item in addrDistrictList" :value="item.id" :key="item.id + 'c'">{{ item.name }}</a-select-option>
                      </a-select>
                    </a-form-item>
                  </a-col>
                </a-form-item>
              </a-row>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="是否卫星仓客户">
                <v-select code="FLAG" id="customerManagementList-satelliteFlag" v-model="queryParam.satelliteFlag" allowClear placeholder="请选择"></v-select>
              </a-form-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-item label="客户类型">
                <a-select v-model="queryParam.customerTypeSn" allowClear placeholder="请选择客户类型">
                  <a-select-option v-for="item in custTypeList" :value="item.customerTypeSn" :key="item.customerTypeSn">{{ item.name }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </template>
          <a-col :md="6" :sm="24" style="margin-bottom: 15px;">
            <a-button type="primary" @click="$refs.table.refresh(true)" :disabled="disabled" id="customerManagementList-refresh">查询</a-button>
            <a-button style="margin-left: 8px" @click="resetSearchForm" :disabled="disabled" id="customerManagementList-reset">重置</a-button>
            <a @click="advanced=!advanced" style="margin-left: 8px">
              {{ 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>
      <!-- <a-button id="customerManagementList-merge" @click="handleMerge" style="margin: 0 0 0 15px;">客户合并</a-button> -->
    </div>
    <!-- 列表 -->
    <s-table
      class="sTable"
      ref="table"
      size="default"
      :rowKey="(record) => record.id"
      :columns="columns"
      :data="loadData"
      :scroll="{ x: 1190, y: tableHeight }"
      bordered>
      <!-- 操作 -->
      <template slot="action" slot-scope="text, record">
        <a-button
          size="small"
          v-if="$hasPermissions('B_customer_customerInfo_edit')"
          type="link"
          class="button-info"
          @click="handleEdit(record)"
          id="customerManagementList-edit-btn">编辑</a-button>
        <a-button
          size="small"
          v-if="$hasPermissions('B_customer_customerInfo_detail')"
          type="link"
          class="button-success"
          @click="handleDetail(record)"
          id="customerManagementList-detail-btn">详情</a-button>
        <a-button
          size="small"
          v-if="$hasPermissions('B_customer_customerInfo_del') && record.satelliteFlag!=1"
          type="link"
          class="button-error"
          @click="handleDel(record)"
          id="customerManagementList-del-btn">删除</a-button>
      </template>
    </s-table>
    <!-- 客户详情 -->
    <customer-management-detail-modal :openModal="openModal" :itemId="itemId" @close="closeModal" />
  </a-card>
</template>

<script>
import moment from 'moment'
import { getArea } from '@/api/data'
import { custList, custDel } from '@/api/customer'
import { custTypeFindAllList } from '@/api/custType'
import { STable, VSelect } from '@/components'
import customerManagementDetailModal from './detailModal.vue'
export default {
  components: { STable, VSelect, customerManagementDetailModal },
  data () {
    return {
      advanced: false, // 高级搜索 展开/关闭
      tableHeight: 0,
      queryParam: { //  查询条件
        customerName: undefined, //  客户名称
        contactName: '', //  联系人
        provinceSn: undefined, //  省
        citySn: undefined, //  市
        countySn: undefined, //  区
        satelliteFlag: undefined, //  是否卫星仓客户
        customerTypeSn: undefined //  客户类型
      },
      disabled: false, //  查询、重置按钮是否可操作
      dateFormat: 'YYYY-MM-DD',
      creatTime: [], //  创建时间
      lastSaleTime: [], //  最后销售时间
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center' },
        { title: '创建时间', dataIndex: 'createDate', width: 160, align: 'center' },
        { title: '客户名称', dataIndex: 'customerName', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '联系人', dataIndex: 'contactName', width: 140, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '联系电话', dataIndex: 'contactTel', width: 140, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '最后销售时间', dataIndex: 'lastSaleTime', width: 160, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '是否卫星仓', dataIndex: 'satelliteFlagDictValue', width: 110, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '操作', scopedSlots: { customRender: 'action' }, width: 200, align: 'center', fixed: 'right' }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        if (this.tableHeight == 0) {
          this.tableHeight = window.innerHeight - 284
        }
        // 创建时间
        if (this.creatTime && this.creatTime.length > 0) {
          this.queryParam.beginDate = moment(this.creatTime[0]).format(this.dateFormat)
          this.queryParam.endDate = moment(this.creatTime[1]).format(this.dateFormat)
        } else {
          this.queryParam.beginDate = undefined
          this.queryParam.endDate = undefined
        }
        // 最后销售时间
        if (this.lastSaleTime && this.lastSaleTime.length > 0) {
          this.queryParam.saleBeginDate = moment(this.lastSaleTime[0]).format(this.dateFormat)
          this.queryParam.saleEndDate = moment(this.lastSaleTime[1]).format(this.dateFormat)
        } else {
          this.queryParam.saleBeginDate = undefined
          this.queryParam.saleEndDate = undefined
        }
        return custList(Object.assign(parameter, this.queryParam)).then(res => {
          const 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
          }
          this.disabled = false
          return data
        })
      },
      addrProvinceList: [], //  省下拉
      addrCityList: [], //  市下拉
      addrDistrictList: [], //  区下拉
      custTypeList: [], //  客户类型 下拉数据
      openModal: false, //  查看客户详情  弹框
      itemId: '' //  当前客户id
    }
  },
  methods: {
    // 不可选日期
    disabledDate (date, dateStrings) {
      return date && date.valueOf() > Date.now()
    },
    //  重置
    resetSearchForm () {
      this.queryParam.customerName = undefined
      this.queryParam.contactName = ''
      this.queryParam.provinceSn = undefined
      this.queryParam.citySn = undefined
      this.queryParam.countySn = undefined
      this.queryParam.satelliteFlag = undefined
      this.queryParam.customerTypeSn = undefined
      this.creatTime = []
      this.lastSaleTime = []
      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 () {
          custDel({ id: row.id }).then(res => {
            if (res.status == 200) {
              _this.$message.success(res.message)
              _this.$refs.table.refresh()
            }
          })
        }
      })
    },
    //  客户合并
    handleMerge () {},
    //  客户信息详情
    handleDetail (row) {
      this.itemId = row.id
      this.openModal = true
    },
    //  关闭弹框
    closeModal () {
      this.itemId = ''
      this.openModal = false
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    //  获取客户类型列表
    getCustTypeList () {
      const _this = this
      custTypeFindAllList().then(res => {
        if (res.status == 200) {
          _this.custTypeList = res.data || []
        } else {
          _this.custTypeList = []
        }
      })
    },
    // 获取城市列表
    getCityList (val) {
      this.addrCityList = []
      this.addrDistrictList = []
      this.queryParam.citySn = undefined
      this.queryParam.countySn = undefined
      this.getArea('city', val)
    },
    // 获取区县列表
    getAreaList (val) {
      this.addrDistrictList = []
      this.queryParam.countySn = undefined
      this.getArea('district', val)
    },
    //  省/市/区
    getArea (type, sn) {
      let params
      if (type == 'province') {
        params = { level: '1' }
      } else {
        params = { psn: sn }
      }
      getArea(params).then(res => {
        if (res.status == 200) {
          if (type == 'province') {
            this.addrProvinceList = res.data || []
          } else if (type == 'city') {
            this.addrCityList = res.data || []
          } else if (type == 'district') {
            this.addrDistrictList = res.data || []
          }
        } else {
          if (type == 'province') {
            this.addrProvinceList = []
          } else if (type == 'city') {
            this.addrCityList = []
          } else if (type == 'district') {
            this.addrDistrictList = []
          }
        }
      })
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.getArea('province')
      vm.getCustTypeList()
    })
  }
}
</script>
