<template>
  <div>

    <el-alert
      title="调整后会立即生成一份审批"
      type="warning"
      show-icon
    />
    <base-list>

      <template slot="n_header">
        <el-form v-model="pagerDto" inline>
          <el-form-item v-if="showSeal" label="业务员">
            <el-select v-model="pagerDto._Eq_SalesmanUserId" placeholder="业务员" clearable filterable>
              <el-option
                v-for="item in salesmanUser"
                :key="item.Id"
                :label="item.NickName"
                :value="item.Id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="客户">
            <el-select v-model="pagerDto._In_CustomerId" placeholder="客户" clearable filterable multiple>
              <el-option
                v-for="item in Customers"
                :key="item.Id"
                :label="item.CompanyName"
                :value="item.Id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="客户是否启用">
            <el-select v-model="pagerDto._Eq_IsActive" placeholder="客户是否启用">
              <el-option
                v-for="item in CustomerActiveOptions"
                :key="item.Id"
                :label="item.Name"
                :value="item.Id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-select
              v-model="pagerDto._In_ExpressId"
              placeholder="线路名称"
              clearable
              filterable
              multiple
            >
              <el-option
                v-for="item in publicChannels"
                :key="item.Id"
                :label="item.Name"
                :value="item.Id"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="渠道是否启用">
            <el-select v-model="pagerDto._Eq_ChannelEnabled" placeholder="渠道是否启用">
              <el-option
                v-for="item in ChannelEnabledOptions"
                :key="item.Id"
                :label="item.Name"
                :value="item.Id"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-input
              v-model="pagerDto._Eq_重量段"
              placeholder="重量段"
              type="text"
              clearable
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="pagerSerach()">搜索</el-button>
          </el-form-item>
        </el-form>
      </template>
      <template v-if="menuIndex==1" slot="n_option">
        <el-button type="primary" size="small" @click="copy()">
          复制
        </el-button>
        <el-button type="primary" size="small" @click="barchChange()">
          批量调整
        </el-button>
      </template>
      <template>
        <el-row :gutter="20">
          <el-col :span="2">
            <div>
              <el-menu style="min-height: 400px; margin-top: -20px;" default-active="1" @select="switchMenu">
                <el-menu-item index="1">
                  <span slot="title">专线/大货</span>
                </el-menu-item>
                <el-menu-item index="2">
                  <span slot="title">邮政</span>
                </el-menu-item>
                <el-menu-item index="3">
                  <span slot="title">快递</span>
                </el-menu-item>
              </el-menu>
            </div>
          </el-col>
          <el-col :span="22">
            <el-table
              v-show="menuIndex==1"
              ref="selectDataTable"
              v-loading="dataLoading"
              row-key="Id"
              border
              :data="data"
              :highlight-current-row="true"
              :select-on-indeterminate="true"
              width="100%"
              :span-method="spanMethod"
              stripe
              @select="changeSelect"
              @select-all="changeSelectAll"
            >
              <el-table-column
                label="操作"
                type="selection"
              />
              <el-table-column label="客户" prop="客户" width="150" />
              <el-table-column label="线路名称" prop="线路名称" width="150" />
              <el-table-column label="运费/KG" prop="运费" width="100" />
              <el-table-column label="操作费/国家" prop="操作费" width="100" />
              <el-table-column label="重量段" prop="重量段" width="150" />
              <el-table-column label="生效时间" prop="生效时间" width="150" />
            </el-table>
            <chinapost
              v-show="menuIndex==2"
              :basedata.sync="baseData"
              :expressid.sync="channelId"
              :chinapostdiscount.sync="thisChinapostdiscount"
              :expressname.sync="expressName"
              :input-customers.sync="Customers"
            />
            <express
              v-show="menuIndex==3"
              :basedata.sync="baseData"
              :expressid.sync="channelId"
              :channelname.sync="expressName"
              :customerids.sync="selectCustomers"
              :customers.sync="Customers"
              :pagerSerach.sync="pagerSerach"
            />
          </el-col>
        </el-row>
      </template>
    </base-list>
    <el-dialog
      title="批量调整"
      :visible.sync="dialogBatchChange"
    >
      <el-form label-position="left">
        <el-form-item label="生效时间">
          <el-date-picker v-model="batchDto.setTime" value-format="yyyy-MM-dd" />
          <span v-show="batchDto.isChange&&!batchDto.setTime" style="color:red">
            *当前报价已变更，必须填入生效时间
          </span>
        </el-form-item>
        <el-form-item label="附件(仅支持单文件，非必填)">
          <el-upload
            class="upload-demo"
            action="http://120.24.149.148/api/Finance/updateLoadFile"
            :on-success="changeCreateBillUrl"
            :multiple="false"
            :show-file-list="false"
          >
            <el-button size="small" type="primary">上传附件</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="从文件导入明细">
          <el-upload
            class="upload-demo"
            action="http://120.24.149.148/api/Finance/updateLoadFile"
            :on-success="importDefailts"
            :multiple="false"
            :show-file-list="false"
          >
            <el-button size="small" type="danger">上传明细</el-button>
          </el-upload>
        </el-form-item>
        <el-form-item label="调整说明(非必填)">
          <el-input v-model="batchDto.Remark" type="textarea" :rows="2" />
        </el-form-item>
      </el-form>
      <el-form v-for="(dto,index) in batchDto.expressFees" :key="index">
        <el-form-item label="调整客户">
          <el-select v-model="dto.ChangeCustomers" placeholder="当前调整客户" clearable filterable multiple>
            <el-option
              v-for="item in Customers"
              :key="item.Id"
              :label="item.CompanyName"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>
        <el-form-item :label="dto.name">
          <el-table :data="dto.detail" border>
            <el-table-column label="开始重量" prop="重量段">
              <template slot-scope="r">
                <el-input-number v-model="r.row.开始重量" size="small" :precision="3" :step="0.001" :controls="false" @change="changeRowData(r.row,dto)" />
              </template>
            </el-table-column>
            <el-table-column label="结束重量" prop="重量段">
              <template slot-scope="r">
                <el-input-number v-model="r.row.结束重量" size="small" :precision="3" :step="0.001" :controls="false" @change="changeRowData(r.row,dto)" />
              </template>
            </el-table-column>
            <el-table-column label="运费/KG" prop="运费">
              <template slot-scope="r">
                <el-input-number v-model="r.row.运费" size="small" :precision="2" :step="0.01" :controls="false" @change="changeRowData(r.row,dto)" />
              </template>
            </el-table-column>
            <el-table-column label="操作费/国家" prop="操作费">
              <template slot-scope="r">
                <el-input v-model="r.row.操作费" size="small" :precision="2" :step="0.01" :controls="false" @change="changeRowData(r.row,dto)" />
              </template>
            </el-table-column>
            <el-table-column label="添加/删除">
              <template slot-scope="r">
                <el-button size="mini" @click="addRow(r.$index,r.row,dto)">+</el-button>
                <el-button size="mini" @click="deleteRow(r.$index,r.row,dto)">-</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogBatchChange = false">取 消</el-button>
        <el-button type="primary" @click="SendDingDing()" :loading="postLoading">提 交</el-button>
      </span>
    </el-dialog>
    <el-dialog
      title="复制报价"
      :visible.sync="dialogCopy"
    >
      <el-form>
        <el-select v-model="copyCustomer" placeholder="复制至客户" clearable filterable multiple>
          <el-option
            v-for="item in Customers"
            :key="item.Id"
            :label="item.CompanyName"
            :value="item.Id"
          />
        </el-select>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogCopy = false">取 消</el-button>
        <el-button type="primary" @click="postCopy()">提 交</el-button>
      </span>
    </el-dialog>
  </div>

</template>
<script>
import { _getCustomers, _getChannel } from '@/api/baseInfo'
import { _getSalesmanUsers } from '@/api/customer'
import { mapGetters } from 'vuex'
import Chinapost from './quotationManagement/chinapost'
import Express from './quotationManagement/express'
import BaseList from '@/components/Xyy/baselist'
import { Query, postBatchChange, ImportExcelToJson, GetChinaPostPublic, QueryChinaPostPublicDiscount, GetFedexBaseFee } from '@/api/financeQuotation'
export default {
  name: 'QuotationManagement',
  components: { 'base-list': BaseList, 'chinapost': Chinapost, 'express': Express },
  computed: {
    ...mapGetters([
      'roles'
    ])
  },
  data() {
    return {
      dialogBatchChange: false,
      data: [], dataLoading: false,
      salesmanUser: [],
      showSeal: true,
      Customers: [],
      publicChannels: [],
      postLoading:false,
      pagerDto: { _Eq_IsActive: '1' },
      attrUrl: '',
      groups: [],
      copyCustomer: [],
      baseData: [],
      menuIndex: '1',
      thisChinapostdiscount: [],
      CustomerActiveOptions: [
        { Id: '1', Name: '已启用' },
        { Id: '0', Name: '未启用' },
        { Id: '', Name: '所有' }
      ],
      ChannelEnabledOptions: [
        { Id: '1', Name: '已启用' },
        { Id: '0', Name: '未启用' },
        { Id: null, Name: '所有' }
      ],
      dialogCopy: false,
      changeFees: [],
      channelId: 0,
      expressName: '',
      selectCustomers: [],
      batchDto: {
        expressFees: [],
        setTime: '',
        isChange: false
        // expressFees:
        //     [{ setTime: null, ChangeCustomers: [1], Id: 30, name: '美国专线', detail: [{ '开始重量': '0.100', '结束重量': '0.200', '运费': '82.00', '操作费': '18.00', '重量段': '0.100-0.200', '生效时间': '2021-11-12' },
        //       { '开始重量': '0.201', '结束重量': '0.450', '运费': '82.00', '操作费': '16.00', '重量段': '0.201-0.450', '生效时间': '2021-11-12' },
        //       { '开始重量': '0.451', '结束重量': '0.700', '运费': '79.00', '操作费': '16.00', '重量段': '0.451-0.700', '生效时间': '2021-11-12' },
        //       { '开始重量': '0.701', '结束重量': '1.000', '运费': '79.00', '操作费': '9.00', '重量段': '0.701-1.000', '生效时间': '2021-11-12' },
        //       { '开始重量': '1.001', '结束重量': '30.000', '运费': '74.00', '操作费': '8.00', '重量段': '1.001-30.000', '生效时间': '2021-11-12' }] }]
      }
    }
  },
  mounted() {
    this.showSeal = !this.roles.includes('销售')
    _getCustomers().then(response => {
      this.Customers = response
    })
    _getSalesmanUsers().then(response => {
      this.salesmanUser = response
    })
    _getChannel().then(res => {
      this.publicChannels = res
    })
  },
  methods: {
    changeSelectAll(s) {
      this.changeFees = s
    },
    changeSelect(s) {
      debugger
      this.changeFees = []
      for (var j = 0; j < s.length; j++) {
        var v = s[j]

        for (var i = 0; i < this.data.length; i++) {
          var n = this.data[i]
          if (n.CustomerId == v.CustomerId) {
            debugger
            this.changeFees.push(n)
          }
        }
      }
    },
    SendDingDing() {
      // 单条更新，我们更新整个报价
      var fillter = JSON.parse(JSON.stringify(this.batchDto.expressFees.filter(x => x.isChange)))
      fillter.forEach(x => {
        x.setTime = this.batchDto.setTime
        x.Remark = this.batchDto.Remark
        x.FileUrl = this.attrUrl
      })
      if (fillter.length > 0 && this.batchDto.setTime == null) {
        this.$message({ type: 'error', message: '请输入生效时间' })
      }
      this.postLoading = true;
      postBatchChange(fillter).then(r => {
        this.$message({ type: 'success', message: '提交成功，等待批复' })
        this.dialogBatchChange = false
        this.pagerSerach()
      }).finally(r=>{
        this.postLoading=false;
      })
    },
    changeRowData(row, dto) {
      dto.isChange = true
      row.isChange = true
      this.batchDto.isChange = true
    },
    addRow(index, row, dto) {
      var r = {
        '开始重量': '',
        '结束重量': '',
        '运费': '',
        '操作费': '',
        isChange: false
      }
      dto.detail.push(r)
      this.changeRowData(r, dto)
    },
    deleteRow(index, row, dto) {
      dto.detail.splice(index, 1)
      dto.detail.forEach(x => { x.isChange = true })
      dto.isChange = true
      this.batchDto.isChange = true
    },
    copy() {
      this.copyCustomer = []
      this.dialogCopy = true
    },
    postCopy() {
      this.barchChange()
      this.batchDto.expressFees.forEach(x => { x.detail.forEach(y => { y.isChange = true }); x.isChange = true })
      this.batchDto.expressFees.forEach(x => { x.ChangeCustomers = this.copyCustomer })
    },
    barchChange() {
      this.batchDto.expressFees.splice(0, this.batchDto.expressFees.length)
      var selects = this.changeFees
      var userChannel = []
      debugger
      // 先按客户和渠道分组
      for (var i = 0; i < selects.length; i++) {
        var item = selects[i]
        var uc = userChannel.filter(x => {
          return x.CustomerId == item.CustomerId && x.ExpressId == item.ExpressId
        })
        if (uc.length == 0) {
          uc = { ExpressId: item.ExpressId, CustomerId: item.CustomerId, '线路名称': item.线路名称, detail: [] }
          userChannel.push(uc)
        } else {
          uc = uc[0]
        }
        uc.detail.push({
          '开始重量': item.重量段.split('-')[0],
          '结束重量': item.重量段.split('-')[1],
          '运费': item.运费,
          '操作费': item.操作费,
          isChange: false
        })
      }

      for (var i2 = 0; i2 < userChannel.length; i2++) {
        var uc2 = userChannel[i2]
        // 计算客户与渠道的HS值
        uc2.detailJson = JSON.stringify(uc2.detail)
        var fees = this.batchDto.expressFees
        var fee = fees.filter(x => { return x.ExpressId == uc2.ExpressId && x.detailJson == uc2.detailJson })
        if (fee.length == 0) {
          fee = { ExpressId: uc2.ExpressId, detailJson: uc2.detailJson, detail: uc2.detail, ChangeCustomers: [uc2.CustomerId], name: uc2.线路名称, setTime: '', isChange: false }
          fees.push(fee)
        } else {
          fee = fee[0]
          fee.ChangeCustomers.push(uc2.CustomerId)
        }
      }
      this.dialogBatchChange = true
    },
    pagerSerach() {
      this.dataLoading = true
      /* 专线/FBA另外处理 */
      if (this.menuIndex == '2') {
        this.channelId = this.pagerDto._In_ExpressId[0]
        debugger
        this.expressName = this.publicChannels.filter(x => x.Id == this.channelId)[0].Name
        // 公开价
        GetChinaPostPublic(this.pagerDto._In_ExpressId[0])
          .then(res => {
            this.baseData = res
          })
          .finally(res => {
            this.dataLoading = false
          })
        // 折扣
        QueryChinaPostPublicDiscount(this.pagerDto)
          .then(res => {
            this.thisChinapostdiscount = res
          }).finally(res => {
            this.dataLoading = false
          })
      } else if (this.menuIndex == '3') {
        this.channelId = this.pagerDto._In_ExpressId[0]
        this.expressName = this.publicChannels.filter(x => x.Id == this.channelId)[0].Name
        this.selectCustomers = this.pagerDto._In_CustomerId
        this.dataLoading = true
        GetFedexBaseFee(this.pagerDto).then(res => {
          this.baseData = res
        }).finally(res => {
          this.dataLoading = false
        })
      } else {
        Query(this.pagerDto).then(res => {
          this.data = res
          this.groups[0] = this.getSpanArr(this.data, '客户')
          this.groups[1] = this.groups[0]
          this.groups[2] = this.getSpanArr(this.data, '线路名称')
        }).finally(res => { this.dataLoading = false })
      }
    },
    getSpanArr(data, prop) {
      var name = ''
      var wf = 0
      var wc = 0
      var spanList = [1]
      for (var i = 0; i < data.length; i++) {
        if (i === 0) {
          name = this.data[i][prop]
          wf = 0
          wc = 1
        } else {
          if (this.data[i][prop] == name) {
          // 相等
            spanList.push(0)
            spanList[wf] = ++wc
          } else {
            name = this.data[i][prop]
            wc = 1
            wf = i
            spanList.push(1)
          }
        }
      }
      return spanList
    },
    changeCreateBillUrl(url) {
      this.attrUrl = url.Data.url
      this.$alert('上传成功')
    },
    importDefailts(url) {
      ImportExcelToJson({ FileUrl: url.Data.url }).then(r => {
        debugger
        var ef0 = this.batchDto.expressFees[0]
        ef0.detail = []
        ef0.isChange = true
        this.batchDto.isChange = true
        r.forEach(x => {
          x.isChange = true
        })
        ef0.detail = r
      })
    },
    switchMenu(index) {
      this.menuIndex = index
    },
    spanMethod(obj) {
      if (obj.columnIndex < 3) {
        var span = this.groups[obj.columnIndex]
        if (span) {
          return {
            rowspan: span[obj.rowIndex],
            colspan: 1
          }
        } else {
          return {
            rowspan: 0,
            colspan: 0
          }
        }
      }
    },
    changePager(v) {
      this.pagerSerach()
    }
  }
}
</script>
