<template>
  <a-card size="small" :bordered="false" class="chainSalesDetailReportList-wrap">
    <a-spin :spinning="spinning" tip="Loading...">
      <a-alert :show-icon="false" type="error" message="注:连锁销售单报表包含急件销售数量、售价,连锁销售明细报表不包含急件销售数量、成本、售价" banner style="margin-bottom: 10px;" />
      <!-- 搜索条件 -->
      <div class="table-page-search-wrapper">
        <a-form-model
          id="chainSalesDetailReportList-form"
          ref="ruleForm"
          :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="dealerSn">
                <a-select
                  placeholder="请选择连锁店"
                  id="chainSalesDetailReportList-dealerSn"
                  allowClear
                  v-model="queryParam.dealerSn"
                  :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-input id="chainSalesDetailReportList-salesTargetName" v-model.trim="queryParam.salesTargetName" allowClear placeholder="请输入客户名称"/>
              </a-form-model-item>
            </a-col>
            <template v-if="advanced">
              <a-col :md="6" :sm="24">
                <a-form-model-item label="客户类型">
                  <a-select id="chainSalesDetailReportList-customerType" v-model="queryParam.salesTargetType" 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-model-item>
              </a-col>
              <a-col :md="12" :sm="24">
                <a-row>
                  <a-form-model-item label="客户所在区" :labelCol="{span: 4}" :wrapperCol="{ span: 20 }">
                    <a-col span="7">
                      <a-form-model-item prop="provinceSn" style="margin: 0;">
                        <a-select v-model="queryParam.provinceSn" @change="getCityList" placeholder="请选择省" allowClear>
                          <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;">
                        <a-select v-model="queryParam.citySn" @change="getAreaList" placeholder="请选择市" allowClear>
                          <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;">
                        <a-select v-model="queryParam.countySn" placeholder="请选择区/县" allowClear>
                          <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>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="收款方式">
                  <a-select id="chainSalesDetailReportList-settleStyleSn" v-model="queryParam.settleStyleSn" allowClear placeholder="请选择收款方式">
                    <a-select-option v-for="item in settleStyleList" :value="item.settleStyleSn" :key="item.settleStyleSn">{{ item.name }}</a-select-option>
                  </a-select>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-item label="产品品牌">
                  <a-select
                    placeholder="请选择产品品牌"
                    id="chainSalesDetailReportList-productBrandSn"
                    allowClear
                    v-model="queryParam.productEntity.productBrandSn"
                    :showSearch="true"
                    option-filter-prop="children"
                    :filter-option="filterOption">
                    <a-select-option v-for="item in productBrandList" :key="item.brandSn" :value="item.brandSn">{{ item.brandName }}</a-select-option>
                  </a-select>
                </a-form-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="chainSalesDetailReportList-productType"
                    placeholder="请选择产品分类"
                    allowClear />
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="产品编码">
                  <a-input id="chainSalesDetailReportList-code" v-model.trim="queryParam.productEntity.code" allowClear placeholder="请输入产品编码"/>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="产品名称">
                  <a-input id="chainSalesDetailReportList-name" v-model.trim="queryParam.productEntity.name" allowClear placeholder="请输入产品名称"/>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="仓库仓位">
                  <a-cascader
                    v-model="queryParam.warehouseCascade"
                    expand-trigger="hover"
                    :options="warehouseCascadeData"
                    :fieldNames="{ label: 'name', value: 'sn', children: 'warehouseLocationList' }"
                    id="chainSalesDetailReportList-warehouseCascade"
                    placeholder="请选择仓库仓位"
                    @change="warehouseCascadeChange"
                    allowClear
                    style="width: 100%;" />
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="单号">
                  <a-input id="chainSalesDetailReportList-salesBillNo" v-model.trim="queryParam.salesBillNo" allowClear placeholder="请输入单号"/>
                </a-form-model-item>
              </a-col>
              <a-col :md="6" :sm="24">
                <a-form-model-item label="业务员">
                  <a-input id="chainSalesDetailReportList-salesManName" v-model.trim="queryParam.salesManName" allowClear placeholder="请输入业务员"/>
                </a-form-model-item>
              </a-col>
            </template>
            <a-col :md="6" :sm="24" style="margin-top: 3px;">
              <a-button type="primary" @click="handleSearch" :disabled="disabled" id="chainSalesDetailReportList-refresh">查询</a-button>
              <a-button style="margin-left: 5px" @click="resetSearchForm" :disabled="disabled" id="chainSalesDetailReportList-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-model>
      </div>
      <!-- 合计 -->
      <a-alert type="info" showIcon style="margin-bottom:10px">
        <div class="ftext" slot="message">
          产品总数量：<strong>{{ (totalData && (totalData.totalQty || totalData.totalQty==0)) ? totalData.totalQty : '--' }}</strong>；
          总成本：<strong>{{ (totalData && (totalData.totalCost || totalData.totalCost==0)) ? '￥'+totalData.totalCost : '--' }}</strong>；
          总售价：<strong>{{ (totalData && (totalData.totalPrice || totalData.totalPrice==0)) ? '￥'+totalData.totalPrice : '--' }}</strong>；
          总毛利：<strong>{{ (totalData && (totalData.totalProfit || totalData.totalProfit==0)) ? '￥'+totalData.totalProfit : '--' }}</strong>。
        </div>
      </a-alert>
      <!-- 列表 -->
      <s-table
        class="sTable"
        ref="table"
        size="small"
        :rowKey="(record) => record.id"
        :columns="columns"
        :data="loadData"
        :scroll="{ x: 1770 }"
        :defaultLoadData="false"
        bordered>
      </s-table>
    </a-spin>
  </a-card>
</template>

<script>
import { STable, VSelect } from '@/components'
import rangeDate from '@/views/common/rangeDate.vue'
import { getArea } from '@/api/data'
import { custTypeFindAllList } from '@/api/custType'
import { settleStyleFindAllList } from '@/api/customer'
import { dealerProductBrandQuery } from '@/api/dealerProductBrand'
import { dealerProductTypeList } from '@/api/dealerProductType'
import { warehouseCascadeList } from '@/api/warehouse'
import { reportSalesBillDetailList, reportSalesBillDetailCount, linkageGroupList } from '@/api/reportData'
export default {
  components: { STable, VSelect, rangeDate },
  data () {
    return {
      spinning: false,
      labelCol: { span: 8 },
      wrapperCol: { span: 16 },
      advanced: false, // 高级搜索 展开/关闭
      tableHeight: 0,
      queryParam: { //  查询条件
        dealerSn: undefined,
        time: [],
        beginDate: '',
        endDate: '',
        salesTargetName: '',
        salesTargetType: undefined,
        provinceSn: undefined, //  省
        citySn: undefined, //  市
        countySn: undefined, //  区
        settleStyleSn: undefined,
        productEntity: {
          productBrandSn: undefined, //  产品品牌
          productTypeSn1: '', //  产品一级分类
          productTypeSn2: '', //  产品二级分类
          productTypeSn3: '', //  产品三级分类
          code: '', //  产品编码
          name: '' //  产品名称
        },
        warehouseCascade: [],
        warehouseSn: undefined,
        warehouseLocationSn: undefined,
        salesBillNo: '',
        salesManName: ''
      },
      rules: {
        'dealerSn': [{ required: true, message: '请选择连锁店', trigger: 'change' }],
        'time': [{ required: true, message: '请选择审核时间', trigger: 'change' }]
      },
      disabled: false, //  查询、重置按钮是否可操作
      exportLoading: false,
      columns: [
        { title: '序号', dataIndex: 'no', width: 80, align: 'center', fixed: 'left' },
        { title: '销售单号', dataIndex: 'salesBillNo', width: 220, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '客户名称', dataIndex: 'salesTargetName', align: 'center', customRender: function (text) { return text || '--' }, ellipsis: true },
        { title: '收款方式', dataIndex: 'settleStyleName', width: 150, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品编码', dataIndex: 'productEntity.code', width: 220, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '产品名称', dataIndex: 'productEntity.name', width: 220, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '单位', dataIndex: 'productEntity.unit', width: 100, align: 'center', customRender: function (text) { return text || '--' } },
        { title: '数量', dataIndex: 'productQty', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? text : '--') } },
        { title: '成本', dataIndex: 'productCost', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? ('￥' + text) : '--') } },
        { title: '售价', dataIndex: 'productPrice', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? ('￥' + text) : '--') } },
        { title: '毛利', dataIndex: 'productProfit', width: 100, align: 'center', customRender: function (text) { return ((text || text == 0) ? ('￥' + text) : '--') } },
        { title: '审核时间', dataIndex: 'salesAuditDate', width: 160, align: 'center', customRender: function (text) { return text || '--' } }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        this.disabled = true
        const params = Object.assign(parameter, this.queryParam)
        this.spinning = true
        delete params.time
        delete params.warehouseCascade
        if (params.dealerSn == 'all') {
          params.dealerSn = ''
        }
        return reportSalesBillDetailList(params).then(res => {
          // 总计
          this.getCount(params)
          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
          this.spinning = false
          return data
        })
      },
      totalData: null, //  合计
      addrProvinceList: [], //  省下拉
      addrCityList: [], //  市下拉
      addrDistrictList: [], //  区下拉
      linkageGroupData: [],
      allocateTypeList: [], //  调拨类型
      custTypeList: [], //  客户类型 下拉数据
      settleStyleList: [], //  收款方式  下拉数据
      productBrandList: [], //  品牌下拉数据
      productType: [],
      productTypeList: [], //  分类下拉数据
      warehouseCascadeData: [] //  仓库仓位
    }
  },
  methods: {
    // 合计
    getCount (params) {
      reportSalesBillDetailCount(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.dealerSn = undefined
      this.$refs.rangeDate.resetDate()
      this.queryParam.time = []
      this.queryParam.beginDate = ''
      this.queryParam.endDate = ''
      this.queryParam.salesTargetName = ''
      this.queryParam.salesTargetType = undefined
      this.queryParam.provinceSn = undefined
      this.queryParam.citySn = undefined
      this.queryParam.countySn = undefined
      this.queryParam.settleStyleSn = undefined
      this.queryParam.productEntity.productBrandSn = undefined
      this.queryParam.productEntity.productTypeSn1 = ''
      this.queryParam.productEntity.productTypeSn2 = ''
      this.queryParam.productEntity.productTypeSn3 = ''
      this.queryParam.productEntity.code = ''
      this.queryParam.productEntity.name = ''
      this.queryParam.warehouseSn = undefined
      this.queryParam.warehouseLocationSn = undefined
      this.queryParam.warehouseCascade = []
      this.queryParam.salesBillNo = ''
      this.queryParam.salesManName = ''
      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
      )
    },
    //  获取客户类型列表
    getCustTypeList () {
      const _this = this
      custTypeFindAllList().then(res => {
        if (res.status == 200) {
          _this.custTypeList = res.data || []
        } else {
          _this.custTypeList = []
        }
      })
    },
    // 收款方式
    getSettleStyleList () {
      settleStyleFindAllList().then(res => {
        if (res.status == 200) {
          this.settleStyleList = res.data
        } else {
          this.settleStyleList = []
        }
      })
    },
    //  产品品牌  列表
    getProductBrand () {
      dealerProductBrandQuery({}).then(res => {
        if (res.status == 200) {
          this.productBrandList = res.data
        } else {
          this.productBrandList = []
        }
      })
    },
    //  产品分类  change
    changeProductType (val, opt) {
      this.queryParam.productEntity.productTypeSn1 = val[0] ? val[0] : ''
      this.queryParam.productEntity.productTypeSn2 = val[1] ? val[1] : ''
      this.queryParam.productEntity.productTypeSn3 = val[2] ? val[2] : ''
    },
    //  产品分类  列表
    getProductType () {
      dealerProductTypeList({}).then(res => {
        if (res.status == 200) {
          this.productTypeList = res.data
        } else {
          this.productTypeList = []
        }
      })
    },
    // 连锁店
    getLinkageGroup () {
      linkageGroupList({}).then(res => {
        const all = [{ dealerName: '全部', dealerSn: 'all' }]
        if (res.status == 200) {
          const data = res.data || []
          this.linkageGroupData = [...all, ...data]
        } else {
          this.linkageGroupData = all
        }
      })
    },
    //  仓库仓位  级联  列表
    getWarehouseCascade () {
      warehouseCascadeList({}).then(res => {
        if (res.status == 200) {
          res.data.map(item => {
            item.sn = item.warehouseSn
            if (item.warehouseLocationList) {
              item.warehouseLocationList.map(subItem => {
                subItem.sn = subItem.warehouseLocationSn
              })
            }
          })
          this.warehouseCascadeData = res.data
        } else {
          this.warehouseCascadeData = []
        }
      })
    },
    // 仓库仓位change
    warehouseCascadeChange (val) {
      if (val && val.length > 0) {
        this.queryParam.warehouseSn = val[0] || ''
        this.queryParam.warehouseLocationSn = val[1] || ''
      } else {
        this.queryParam.warehouseSn = ''
        this.queryParam.warehouseLocationSn = ''
      }
    },
    // 获取城市列表
    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 = []
          }
        }
      })
    }
  },
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.getLinkageGroup()
      vm.getArea('province')
      vm.getCustTypeList()
      vm.getSettleStyleList()
      vm.getProductBrand()
      vm.getProductType()
      vm.getWarehouseCascade()
    })
  }
}
</script>
