<template>
  <a-card size="small" :bordered="false" class="customerReportList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper">
        <a-form-model
          id="customerReportList-form"
          ref="ruleForm"
          class="form-model-con"
          layout="inline"
          :model="queryParam"
          :rules="rules"
          :labelCol="labelCol"
          :wrapperCol="wrapperCol"
          @keyup.enter.native="handleSearch" >
          <a-row :gutter="15">
            <a-col :md="6" :sm="24">
              <a-form-model-item label="连锁店" prop="tenantId">
                <a-select
                  placeholder="请选择连锁店"
                  id="customerReportList-tenantId"
                  allowClear
                  v-model="queryParam.tenantId"
                  :showSearch="true"
                  option-filter-prop="children"
                  :filter-option="filterOption">
                  <a-select-option v-for="item in linkageGroupData" :key="item.dealerSn" :value="item.dealerSn">{{ item.dealerName }}</a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="添加时间" prop="time">
                <rangeDate ref="rangeDate" @change="dateChange" />
              </a-form-model-item>
            </a-col>
            <a-col :md="6" :sm="24">
              <a-form-model-item label="产品分类">
                <a-cascader
                  @change="changeProductType"
                  change-on-select
                  v-model="productType"
                  expand-trigger="hover"
                  :options="productTypeList"
                  :fieldNames="{ label: 'productTypeName', value: 'productTypeSn', children: 'children' }"
                  id="customerReportList-productType"
                  placeholder="请选择产品分类"
                  allowClear />
              </a-form-model-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="12" :sm="24">
                <a-row>
                  <a-form-model-item label="客户所在区" :labelCol="{span: 4}" :wrapperCol="{ span: 20 }" style="margin-bottom: 0!important;">
                    <a-col span="7">
                      <a-form-model-item prop="provinceSn" style="margin: 0!important;">
                        <a-select v-model="queryParam.provinceSn" allowClear @change="getCityList" placeholder="请选择省">
                          <a-select-option v-for="item in addrProvinceList" :value="item.areaSn" :key="item.areaSn + 'a'">{{ item.name }}</a-select-option>
                        </a-select>
                      </a-form-model-item>
                    </a-col>
                    <a-col span="7" offset="1">
                      <a-form-model-item prop="citySn" style="margin: 0!important;">
                        <a-select v-model="queryParam.citySn" allowClear @change="getAreaList" placeholder="请选择市">
                          <a-select-option v-for="item in addrCityList" :value="item.areaSn" :key="item.areaSn + 'b'">{{ item.name }}</a-select-option>
                        </a-select>
                      </a-form-model-item>
                    </a-col>
                    <a-col span="7" offset="1">
                      <a-form-model-item prop="countySn" style="margin: 0!important;">
                        <a-select v-model="queryParam.countySn" allowClear placeholder="请选择区/县">
                          <a-select-option v-for="item in addrDistrictList" :value="item.areaSn" :key="item.areaSn + 'c'">{{ item.name }}</a-select-option>
                        </a-select>
                      </a-form-model-item>
                    </a-col>
                  </a-form-model-item>
                </a-row>
              </a-col>
            </template>
            <a-col :md="6" :sm="24" style="margin-bottom: 10px;">
              <a-button type="primary" @click="handleSearch" :disabled="disabled" id="customerReportList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="customerReportList-reset">重置</a-button>
              <a @click="advanced=!advanced" style="margin-left: 5px">
                {{ advanced ? '收起' : '展开' }}
                <a-icon :type="advanced ? 'up' : 'down'"/>
              </a>
            </a-col>
          </a-row>
        </a-form-model>
      </div>
      <!-- 合计 -->
      <a-alert type="info" style="margin-bottom:10px">
        <div class="ftext" slot="message">
          总交易金额：<strong>{{ (totalData && (totalData.totalAmount || totalData.totalAmount==0)) ? totalData.totalAmount : '--' }}</strong>；
          总毛利率：<strong>{{ (totalData && totalData.percentage) ? totalData.percentage+'%' : '--' }}</strong>
        </div>
      </a-alert>
      <!-- 列表 -->
      <s-table
        class="sTable"
        ref="table"
        size="small"
        :rowKey="(record) => record.salesTargetSn"
        :columns="columns"
        :data="loadData"
        :defaultLoadData="false"
        bordered>
      </s-table>
    </a-spin>
  </a-card>
</template>

<script>
import { commonMixin } from '@/utils/mixin'
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import { getArea } from '@/api/data'
import { dealerProductTypeList } from '@/api/dealerProductType'
import { reportBigCustomerLinkageList, reportBigCustomerLinkageCount, linkageGroupList } from '@/api/reportData'
export default {
  components: { STable, VSelect, rangeDate },
  mixins: [commonMixin],
  data () {
    return {
      spinning: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      advanced: true, // 高级搜索 展开/关闭
      tableHeight: 0,
      queryParam: { //  查询条件
        tenantId: undefined,
        time: [],
        beginDate: '',
        endDate: '',
        productTypeSn1: '', //  产品一级分类
        productTypeSn2: '', //  产品二级分类
        productTypeSn3: '', //  产品三级分类
        provinceSn: undefined, //  省
        citySn: undefined, //  市
        countySn: undefined //  区
      },
      productType: [],
      rules: {
        'tenantId': [{ required: true, message: '请选择连锁店', trigger: 'change' }],
        'time': [{ required: true, message: '请选择添加时间', trigger: 'change' }]
      },
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false,
      columns: [
        { title: '序号', dataIndex: 'no', width: '10%', align: 'center' },
        { title: '连锁门店', dataIndex: 'dealerName', width: '25%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '客户名称', dataIndex: 'salesTargetName', width: '25%', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true, sorter: true },
        { title: '交易金额', dataIndex: 'totalAmount', width: '20%', align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') }, sorter: true },
        { title: '毛利率', dataIndex: 'percentageUnit', width: '20%', align: 'center', customRender: function (text) { return text || '--' }, sorter: true }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        const params = Object.assign(parameter, this.queryParam)
        this.spinning = true
        delete params.time
        if (params.beginDate) {
          return reportBigCustomerLinkageList(params).then(res => {
            let data
            if (res.status == 200) {
              data = res.data
              // 总计
              this.getCount(params)
              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].percentageUnit = data.list[i].percentage ? data.list[i].percentage + '%' : undefined
              }
              this.disabled = false
            }
            this.spinning = false
            return data
          })
        } else {
          const _this = this
          return new Promise(function (resolve, reject) {
            const data = {
              pageNo: 1,
              pageSize: 10,
              list: [],
              count: 0
            }
            _this.disabled = false
            _this.spinning = false
            _this.$message.info('请选择添加时间')
            resolve(data)
          })
        }
      },
      totalData: null, //  合计
      addrProvinceList: [], //  省下拉
      addrCityList: [], //  市下拉
      addrDistrictList: [], //  区下拉
      productTypeList: [], //  分类下拉数据
      linkageGroupData: []
    }
  },
  methods: {
    // 合计
    getCount (params) {
      reportBigCustomerLinkageCount(params).then(res => {
        if (res.status == 200) {
          this.totalData = res.data
        } else {
          this.totalData = null
        }
      })
    },
    //  创建时间  change
    dateChange (date) {
      this.queryParam.time = date
      this.queryParam.beginDate = date[0] || ''
      this.queryParam.endDate = date[1] || ''
    },
    //  查询
    handleSearch () {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.$refs.table.refresh(true)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    //  重置
    resetSearchForm () {
      this.queryParam.tenantId = undefined
      this.$refs.rangeDate.resetDate()
      this.queryParam.time = []
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.queryParam.productTypeSn1 = ''
      this.queryParam.productTypeSn2 = ''
      this.queryParam.productTypeSn3 = ''
      this.queryParam.provinceSn = undefined
      this.queryParam.citySn = undefined
      this.queryParam.countySn = undefined
      this.productType = []
      this.$refs.ruleForm.resetFields()
      this.totalData = null
      this.$refs.table.clearTable()
    },
    filterOption (input, option) {
      return (
        option.componentOptions.children[0].text.toLowerCase().indexOf(input.toLowerCase()) >= 0
      )
    },
    //  产品分类  change
    changeProductType (val, opt) {
      this.queryParam.productTypeSn1 = val[0] ? val[0] : ''
      this.queryParam.productTypeSn2 = val[1] ? val[1] : ''
      this.queryParam.productTypeSn3 = val[2] ? val[2] : ''
    },
    //  产品分类  列表
    getProductType () {
      dealerProductTypeList({}).then(res => {
        if (res.status == 200) {
          this.productTypeList = res.data
        } else {
          this.productTypeList = []
        }
      })
    },
    // 获取城市列表
    getCityList (val) {
      this.addrCityList = []
      this.addrDistrictList = []
      this.queryParam.citySn = undefined
      this.queryParam.countySn = undefined
      if (val) {
        this.getArea('city', val)
      }
    },
    // 获取区县列表
    getAreaList (val) {
      this.addrDistrictList = []
      this.queryParam.countySn = undefined
      if (val) {
        this.getArea('district', val)
      }
    },
    //  省/市/区
    getArea (leve, sn) {
      let params
      if (leve == 'province') {
        params = { type: '2' }
      } else {
        params = { parentId: sn, type: leve == 'city' ? '3' : '4' }
      }
      getArea(params).then(res => {
        if (res.status == 200) {
          if (leve == 'province') {
            this.addrProvinceList = res.data || []
          } else if (leve == 'city') {
            this.addrCityList = res.data || []
          } else if (leve == 'district') {
            this.addrDistrictList = res.data || []
          }
        } else {
          if (leve == 'province') {
            this.addrProvinceList = []
          } else if (leve == 'city') {
            this.addrCityList = []
          } else if (leve == 'district') {
            this.addrDistrictList = []
          }
        }
      })
    },
    // 连锁店
    getLinkageGroup () {
      linkageGroupList({}).then(res => {
        if (res.status == 200) {
          this.linkageGroupData = res.data || []
        } else {
          this.linkageGroupData = []
        }
      })
    },
    pageInit () {
      this.getLinkageGroup()
      this.getArea('province')
      this.getProductType()
    }
  },
  mounted () {
    if (!this.$store.state.app.isNewTab) { // 页签刷新时调用
      this.pageInit()
      this.resetSearchForm()
    }
  },
  activated () {
    // 如果是新页签打开，则重置当前页面
    if (this.$store.state.app.isNewTab) {
      this.pageInit()
      this.resetSearchForm()
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {})
  }
}
</script>
