<template>
  <base-list>
    <template slot="n_header">
      <el-form v-model="pagerDto" inline>
        <el-form-item label="渠道">
          <el-select
            v-model="pagerDto._Eq_PublicCode"
            size="mini"
            placeholder="下单渠道"
            clearable
            filterable
          >
            <el-option
              v-for="item in channels"
              :key="item.Code"
              :label="item.Name"
              :value="item.Code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="作用节点">
          <el-select
            v-model="pagerDto._Eq_Node"
            placeholder="作用节点"
            clearable
          >
            <el-option
              v-for="item in nodes"
              :key="item.key"
              :label="item.name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="限定客户">
          <el-select
            v-model="pagerDto._Co_CustomerNumberList"
            placeholder="客户名称"
            clearable
            filterable
          >
            <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._Co_ExcludeCustomerNumberList"
            placeholder="客户名称"
            clearable
            filterable
          >
            <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._Co_countrySpilt"
            placeholder="国家"
            filterable
            multiple
          >
            <el-option
              v-for="item in countrys"
              :key="item.Id"
              :label="item.CnName"
              :value="item.Code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="匹配顺序">
          <el-select
            v-model="pagerDto._Eq_ChannelSort"
            placeholder="匹配顺序"
            filterable
            clearable
          >
            <el-option
              v-for="item in sorts"
              :key="item.key"
              :label="item.name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-select v-model="pagerDto._Eq_Enable" clearable>
            <el-option value="1" label="是" />
            <el-option value="0" label="否" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            :loading="dataLoading"
            type="primary"
            size="mini"
            @click="pagerSerach(1)"
          >搜索</el-button>
        </el-form-item>
      </el-form>
    </template>
    <template slot="n_option">
      <el-button type="primary" @click="add">添加</el-button>
      <el-button
        id="batchEnable"
        type="success"
        @click="batchSetEnable(true)"
      >批量启用</el-button>
      <el-button
        id="batchDisable"
        type="danger"
        @click="batchSetEnable(false)"
      >批量停用</el-button>
      <el-button
        id="btnBatchRemove"
        type="danger"
        @click="batchRemove(false)"
      >批量移除</el-button>
    </template>
    <template>
      <el-table
        ref="multipleTable"
        v-loading="dataLoading"
        :data="data"
        :highlight-current-row="true"
        :select-on-indeterminate="true"
        width="100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="PublicName" label="渠道" />
        <el-table-column prop="ChannelName" label="转换渠道">
          <template slot-scope="r">
            <div v-if="!r.row.IsZoneGroup">{{ r.row.ChannelName }}</div>
            <el-tag v-else>分区分组匹配</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="CountryCodes" label="国家列表" width="100" />
        <el-table-column prop="StartWeight" label="最小重量" width="100" />
        <el-table-column prop="EndWeight" label="最大重量" width="100" />
        <el-table-column prop="Enable" label="是否启用">
          <template slot-scope="r">
            <el-tag v-if="r.row.Enable == true" type="success">启用</el-tag>
            <el-tag v-else type="danger">不启用</el-tag>
            <!-- {{ r.row.Enable ? "启用" : "不启用" }} -->
          </template>
        </el-table-column>
        <el-table-column prop="ChannelSort" label="匹配顺序">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.ChannelSort == -3" type="info">最最末</el-tag>
            <el-tag v-if="scope.row.ChannelSort == -2" type="info">最末</el-tag>
            <el-tag
              v-if="scope.row.ChannelSort == -1"
              type="danger"
            >次末</el-tag>
            <el-tag
              v-if="scope.row.ChannelSort == 0"
              type="warning"
            >一般</el-tag>
            <el-tag v-if="scope.row.ChannelSort == 1">次优</el-tag>
            <el-tag
              v-if="scope.row.ChannelSort == 2"
              type="success"
            >最优</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="作用节点">
          <template slot-scope="r">
            <el-tag v-if="r.row.Node == 1" type="primary">下单</el-tag>
            <el-tag
              v-else-if="r.row.Node == 2"
              type="primary"
              effect="dark"
            >转单</el-tag>
            <el-tag v-else type="default">无</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="ChannelQty" label="限定数量">
          <template slot-scope="r">
            <div :class="{ 'mark-channel-qty': r.row.ChannelQty > 0 }">
              {{ r.row.ChannelQty }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="SalesmanUserNameList" label="限定业务员" />
        <el-table-column prop="CustomerNameList" label="限定客户" />
        <el-table-column prop="ExcludeCustomerNameList" label="排除客户" />
        <el-table-column prop="ZipHelperAreaList" label="分区服务">
          <template slot-scope="r">
            <span>{{ getZipHelperServiceName(r.row) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="ZipHelperAreaList" label="限定分区" />
        <el-table-column width="120">
          <template slot-scope="r">
            <el-button type="text" @click="editItem(r.row)"> 编辑 </el-button>
            <el-button type="button" size="mini" @click="removeItem(r.row)">
              移除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :page-sizes="[10, 20, 40, 100, 400]"
        :current-page="pagerDto.PageIndex"
        :page-size.sync="pagerDto.PageSize"
        background
        layout="prev, pager, next ,total ,jumper,sizes,slot "
        :total="pagerDto.total"
        @size-change="changePager"
        @current-change="pagerSerach"
      />
    </template>
    <el-dialog :visible.sync="dialogEdit">
      <el-form label-position="left" label-width="100px">
        <el-input v-model="editDto.Id" type="hidden" />
        <el-form-item label="下单渠道">
          <el-select
            v-model="editDto.PublicCode"
            placeholder="下单渠道"
            clearable
            filterable
          >
            <el-option
              v-for="item in channels"
              :key="item.Code"
              :label="item.Name"
              :value="item.Code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="分区分组匹配">
          <el-checkbox v-model="editDto.IsZoneGroup">是</el-checkbox>
        </el-form-item>
        <el-form-item v-if="!editDto.IsZoneGroup" label="转换渠道">
          <el-select
            v-model="editDto.ChannelId"
            placeholder="转换渠道"
            clearable
            filterable
          >
            <el-option
              v-for="item in deliverChannel"
              :key="item.Id"
              :label="item.PublicName"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="国家">
          <el-select
            v-model="editDto.countrySpilt"
            placeholder="国家"
            filterable
            multiple
          >
            <el-option
              v-for="item in countrys"
              :key="item.Id"
              :label="item.CnName"
              :value="item.Code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="作用节点">
          <el-select v-model="editDto.Node" placeholder="作用节点" clearable>
            <el-option
              v-for="item in nodes"
              :key="item.key"
              :label="item.name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="最小重量" label-width="140">
          <el-input v-model="editDto.StartWeight" />
        </el-form-item>
        <el-form-item label="最大重量" label-width="140">
          <el-input v-model="editDto.EndWeight" />
        </el-form-item>
        <el-form-item label="下单数量">
          <el-input v-model="editDto.ChannelQty" type="number" />
        </el-form-item>
        <el-form-item label="支持POBOX地址" label-width="120px">
          <el-checkbox v-model="editDto.CanPOBox">支持</el-checkbox>
        </el-form-item>
        <el-form-item label="是否启用">
          <el-checkbox v-model="editDto.Enable">启用</el-checkbox>
        </el-form-item>
        <el-form-item label="匹配顺序">
          <el-select
            v-model="editDto.ChannelSort"
            placeholder="匹配顺序"
            filterable
          >
            <el-option
              v-for="item in sorts"
              :key="item.key"
              :label="item.name"
              :value="item.key"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="标签代码">
          <el-input v-model="editDto.LabelCode" />
        </el-form-item>
        <el-form-item label="限定业务员所有客户">
          <el-select
            v-model="editDto.SalesmanUserIdSpilt"
            placeholder="业务员"
            clearable
            filterable
            multiple
          >
            <el-option
              v-for="item in salesmanUserIds"
              :key="item.Id"
              :label="item.NickName"
              :value="item.Id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="限定指定客户">
          <el-select
            v-model="editDto.CustomerNameSpilt"
            placeholder="限定指定客户"
            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="editDto.ExcludeCustomerNameSpilt"
            placeholder="限定指定客户"
            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 v-if="!editDto.IsZoneGroup" label="分区服务">
          <el-select
            v-model="editDto.ZipHelperService"
            placeholder="分区服务"
            filterable
            clearable
            @change="changeService"
          >
            <el-option
              v-for="item in zipHelperList"
              :key="item.Name"
              :label="item.Name"
              :value="item.FullName"
            >
              <span style="float: left">{{ item.Name }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{
                item.Describe
              }}</span>
            </el-option>
          </el-select>
          <el-tag type="info">
            {{ zipAreaDescribe }}
          </el-tag>
        </el-form-item>
        <el-form-item v-if="!editDto.IsZoneGroup" label="限制分区">
          <el-select
            v-model="editDto.ZipHelperArea"
            placeholder="限制分区"
            filterable
            multiple
          >
            <el-option
              v-for="item in canSelectAreas"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <el-form v-if="editDto.IsZoneGroup">
        <div class="itemGroup">
          <el-divider content-position="left">分组分区</el-divider>
          <div v-for="(children, index) in editDto.childrens" :key="index">
            <el-divider v-if="index > 0" />
            <el-form-item label="转换渠道">
              <el-select
                v-model="children.ChannelId"
                placeholder="转换渠道"
                clearable
                filterable
              >
                <el-option
                  v-for="item in deliverChannel"
                  :key="item.Id"
                  :label="item.PublicName"
                  :value="item.Id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="匹配顺序">
              <el-select
                v-model="children.ChannelSort"
                placeholder="匹配顺序"
                filterable
                @change="setcanFeeTypesDisabled()"
              >
                <el-option
                  v-for="item in sorts"
                  :key="item.key"
                  :label="item.name"
                  :value="item.key"
                  :disabled="item.disabled"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="分区服务">
              <el-select
                v-model="children.ZipHelperService"
                placeholder="分区服务"
                filterable
                clearable
                @change="changeService"
              >
                <el-option
                  v-for="item in zipHelperList"
                  :key="item.Name"
                  :label="item.Name"
                  :value="item.FullName"
                >
                  <span style="float: left">{{ item.Name }}</span>
                  <span style="float: right; color: #8492a6; font-size: 13px">{{
                    item.Describe
                  }}</span>
                </el-option>
              </el-select>
              <el-tag type="info">
                {{ zipAreaDescribe }}
              </el-tag>
            </el-form-item>
            <el-form-item label="限制分区">
              <el-select
                v-model="children.ZipHelperArea"
                placeholder="限制分区"
                filterable
                multiple
              >
                <el-option
                  v-for="item in canSelectAreas"
                  :key="item"
                  :label="item"
                  :value="item"
                />
              </el-select>
            </el-form-item>
            <el-form v-if="index > 0">
              <el-button
                size="mini"
                icon="el-icon-minus"
                type="danger"
                @click="ExpenseResultDelete(children)"
              >删除</el-button>
            </el-form>
          </div>
        </div>
      </el-form>
      <el-button
        v-if="editDto.IsZoneGroup"
        @click="addBillIncidentalFee()"
      >新增分组分区</el-button>
      <el-button type="primary" @click="save">保存</el-button>
    </el-dialog>
  </base-list>
</template>
<script>
import BaseList from '@/components/Xyy/baselist'
import {
  GetMathList,
  EditSonMath,
  DeleteSonMath,
  _batchEnable,
  _batchDisable,
  _batchRemove,
  _GetChildrenList
} from '@/api/channel/express'

import {
  _getAllPublic,
  _getDeliverChannel,
  _getCountries,
  _getCustomers,
  _getChannelType,
  _getZipHelpels,
  _getUserInfos
} from '@/api/baseInfo'
export default {
  name: 'Express',
  components: { 'base-list': BaseList },
  data() {
    return {
      nodes: [
        { key: 1, name: '下单' },
        { key: 2, name: '转单' }
      ],
      multipleSelection: [],
      dialogEdit: false,
      data: [],
      dataLoading: false,
      channels: [],
      deliverChannel: [],
      countrys: [],
      customers: [],
      zipAreaDescribe: '',
      zipHelperList: [],
      canSelectAreas: [],
      channelType: [],
      salesmanUserIds: [],
      editDto: {
        SalesmanUserIdSpilt: [],
        CustomerNameSpilt: [],
        ExcludeCustomerNameSpilt: [],
        countrySpilt: [],
        CanPOBox: true,
        childrens: [
          {
            ChannelId: 0,
            ChannelSort: 0,
            ZipHelperService: '',
            ZipHelperArea: ''
          }
        ]
      },
      sorts: [
        { name: '最优', key: 2, disabled: false },
        { name: '次优', key: 1, disabled: false },
        { name: '一般', key: 0, disabled: false },
        { name: '次末', key: -1, disabled: false },
        { name: '最末', key: -2, disabled: false },
        { name: '最最末', key: -3, disabled: false }
      ],
      pagerDto: {
        PageIndex: 0,
        PageSize: 20,
        total: 0,
        _Eq_Enable: '1',
        _Eq_Node: 1
      }
    }
  },
  mounted() {
    this.pagerSerach(1)
    _getZipHelpels().then((r) => {
      this.zipHelperList = r
    })
    _getAllPublic().then((resp) => {
      this.channels = resp
    })
    _getDeliverChannel().then((res) => {
      this.deliverChannel = res
    })
    _getCountries().then((res) => {
      this.countrys = res
    })
    _getCustomers().then((res) => {
      this.customers = res
    })
    _getChannelType().then((res) => {
      this.channelType = res
    })
    _getUserInfos('销售').then((res) => {
      this.salesmanUserIds = res
    })
  },
  methods: {
    // 页面动效部分 start
    addBillIncidentalFee() {
      if (this.sorts && this.sorts.filter((x) => !x.disabled).length > 0) {
        this.editDto.childrens.push({
          ChannelId: null,
          ChannelSort: null,
          ZipHelperService: '',
          ZipHelperArea: []
        })
      }
    },
    ExpenseResultDelete(row) {
      var index = this.editDto.childrens.findIndex((x) => x == row)
      this.editDto.childrens.splice(index, 1)
      this.setcanFeeTypesDisabled()
    },
    setcanFeeTypesDisabled() {
      if (this.sorts.length > 0) {
        this.sorts.forEach((ele) => {
          var select = this.editDto.childrens.find(
            (x) => x.ChannelSort == ele.key
          )
          if (select != null) {
            ele.disabled = true
          } else {
            ele.disabled = false
          }
        })
      }
    },
    // 页面动效部分 end
    getZipHelperServiceName(r) {
      // console.log(r, this.zipHelperList);
      const idx = this.zipHelperList.findIndex(
        (i) => i.FullName == r.ZipHelperService
      )
      if (idx > -1) {
        return this.zipHelperList[idx].Name
      } else return null
    },
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    batchRemove() {
      if (!this.multipleSelection || this.multipleSelection.length == 0) {
        this.$message({ type: 'error', message: '请先选择' })
        return
      } else {
        var ld = this.$loading({
          target: '#btnBatchRemove',
          fullscreen: false
        })
        const ids = this.multipleSelection.map((i) => i.Id)
        const data = { ids }
        _batchRemove(data)
          .then((r) => {
            this.$alert('移除成功')
            this.pagerSerach()
          })
          .finally(() => {
            ld.close()
          })
      }
    },
    batchSetEnable(isEnable) {
      if (!this.multipleSelection || this.multipleSelection.length == 0) {
        this.$message({ type: 'error', message: '请先选择' })
        return
      } else {
        const tips =
          isEnable == true ? '是否批量启用所选项?' : '是否批量停用所选项?'
        this.$confirm(tips).then((res) => {
          {
            const btn = isEnable == true ? '#batchEnable' : '#batchDisable'
            const api = isEnable == true ? _batchEnable : _batchDisable

            const ld = this.$loading({ target: btn, fullscreen: false })
            const ids = this.multipleSelection.map((i) => i.Id)
            const data = { ids }

            api(data)
              .then((res) => {
                for (const i of this.multipleSelection) {
                  i.Enable = isEnable
                }
                this.multipleSelection = []
                this.$refs.multipleTable.clearSelection()
                this.$message({ type: 'success', message: '成功' })
              })
              .catch((res) => {
                this.$message({ type: 'error', message: '失败' })
              })
              .finally(() => {
                ld.close()
              })
          }
        })
      }
    },
    changeService(v) {
      debugger
      this.zipAreaDescribe = ''
      this.canSelectAreas = null
      for (var i = 0; i < this.zipHelperList.length; i++) {
        if (v == this.zipHelperList[i].FullName) {
          var item = this.zipHelperList[i]
          this.zipAreaDescribe = item.Describe
          this.canSelectAreas = item.CanSelectZone.split(',')
        }
      }
    },
    save() {
      EditSonMath(this.editDto).then((r) => {
        this.$alert('调整成功')
        this.pagerSerach()
        this.dialogEdit = false
      })
    },
    add() {
      this.editDto = {
        CustomerNameSpilt: [],
        ExcludeCustomerNameSpilt: [],
        countrySpilt: [],
        CanPOBox: true,
        SalesmanUserIdSpilt: [],
        Enable: false,
        childrens: [
          {
            ChannelId: null,
            ChannelSort: null,
            ZipHelperService: '',
            ZipHelperArea: []
          }
        ]
      }
      this.dialogEdit = true
    },
    editItem(row) {
      this.editDto = row
      _GetChildrenList(row.Id).then((res) => {
        this.editDto.childrens = res
        this.setcanFeeTypesDisabled()
      })
      this.dialogEdit = true
    },
    removeItem(row) {
      this.$confirm('是否确定移除该规则').then((r) => {
        DeleteSonMath(row).then((x) => {
          this.$alert('移除成功')
          this.pagerSerach()
        })
      })
    },
    pagerSerach(index) {
      this.dataLoading = true
      if (index) {
        this.pagerDto.PageIndex = index
      }
      GetMathList(this.pagerDto)
        .then((res) => {
          this.data = res.Result
          this.pagerDto.total = res.TotalCount
        })
        .finally((res) => {
          this.dataLoading = false
        })
    },
    changePager(v) {
      this.PageSize = v
      this.pagerSerach()
    }
  }
}
</script>
<style scoped>
.mark-channel-qty {
  color: red;
}
</style>
