<template>
  <div class="app-container">
    <div>
      <el-form inline :model="pagerDto">
        <el-form-item label="源渠道">
          <el-select v-model="pagerDto._Eq_ChannelId" placeholder="源渠道" clearable filterable>
            <el-option
              v-for="item in channels"
              :key="'channel1'+item.Id"
              :value="item.Id"
              :label="item.Name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="目标渠道">
          <el-select v-model="pagerDto._Eq_TargetChannelId" placeholder="目标渠道" clearable filterable>
            <el-option
              v-for="item in channels"
              :key="'channel2'+item.Id"
              :value="item.Id"
              :label="item.Name"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="节点">
          <el-select v-model="pagerDto._Eq_RuleNode" placeholder="节点" clearable filterable>
            <el-option v-for="item in nodes" :key="item.Id" :value="item.Id" :label="item.Name" />
          </el-select>
        </el-form-item>
        <el-form-item label="规则类型">
          <el-select v-model="pagerDto._Eq_RuleType" placeholder="规则类型" clearable filterable>
            <el-option v-for="item in types" :key="item.Id" :value="item.Id" :label="item.Name" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button icon="el-icon-search" size="small" type="primary" @click="pagerSerach()">搜索</el-button>
          <el-button
            icon="el-icon-circle-plus-outline"
            size="small"
            type="success"
            @click="showAddPanel"
          >新增</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-table v-loading="loading" border :data="sourceData">
        <el-table-column label="源渠道" prop="ChannelName" />
        <el-table-column label="目标渠道" prop="TargetChannelName" />
        <el-table-column label="节点" prop="NodeName" />
        <el-table-column label="规则类型" prop="TypeName" />
        <el-table-column label="客户" prop="CustomerNames" />
        <el-table-column label="最小重量" prop="MinWeight" />
        <el-table-column label="最大重量" prop="MaxWeight" />
        <el-table-column label="国家" prop="CountryCodes" />
        <el-table-column label="是否启用" prop="Enable" />
        <el-table-column label="操作" width="200">
          <template slot-scope="scope">
            <el-button @click="edit(scope.row)">编辑</el-button>
            <el-button type="danger" plain @click="remove(scope.row)">移除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div>
      <el-pagination
        :page-sizes="[100, 200, 300, 400]"
        :current-page="pagerDto.PageIndex"
        :page-size="pagerDto.PageSize"
        background
        layout="prev, pager, next ,total ,jumper,sizes,slot "
        :total="pagerDto.total"
        @current-change="pagerSerach"
      />
    </div>
    <el-dialog :visible.sync="showEditPannel">
      <el-form
        ref="editForm"
        v-loading="submiting"
        label-width="6em"
        :model="editItem"
        :rules="rules"
      >
        <el-form-item label="渠道" prop="ChannelId">
          <el-select v-model="editItem.ChannelId" filterable>
            <el-option v-for="item in channels" :key="item.Id" :label="item.Name" :value="item.Id" />
          </el-select>
        </el-form-item>
        <el-form-item label="目标渠道" prop="TargetChannelId">
          <el-select v-model="editItem.TargetChannelId" filterable>
            <el-option v-for="item in channels" :key="item.Id" :label="item.Name" :value="item.Id" />
          </el-select>
        </el-form-item>
        <el-form-item label="规则节点" prop="RuleNode">
          <el-select v-model="editItem.RuleNode" filterable>
            <el-option v-for="item in nodes" :key="item.Id" :label="item.Name" :value="item.Id" />
          </el-select>
        </el-form-item>
        <el-form-item label="规则类型" prop="RuleType">
          <el-select v-model="editItem.RuleType">
            <el-option v-for="item in types" :key="item.Id" :label="item.Name" :value="item.Id" />
          </el-select>
        </el-form-item>
        <el-form-item label="国家" prop="CountryCodeValues">
          <el-select v-model="editItem.CountryCodeValues" multiple filterable>
            <el-option
              v-for="(item,index) in countries"
              :key="index"
              :label="item.CnName"
              :value="item.Code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="客户" prop="CustomerIdValues">
          <el-select v-model="editItem.CustomerIdValues" multiple filterable>
            <el-option
              v-for="item in customers"
              :key="item.CustomerNumber"
              :label="item.CustomerNumber"
              :value="item.Id"
            >
              <span style="float: left">{{ item.CustomerNumber }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.CompanyName }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <div>
          <el-form-item label="重量  从" prop="MinWeight" style="display:inline-block">
            <el-input v-model="editItem.MinWeight" maxlength="6" style="width:6em" />
          </el-form-item>

          <el-form-item label="到" prop="MaxWeight" style="display:inline-block">
            <el-input v-model="editItem.MaxWeight" maxlength="6" style="width:6em" />
          </el-form-item>
        </div>
        <el-form-item label="是否启用">
          <el-checkbox v-model="editItem.Enabled" />
        </el-form-item>
        <el-form-item label="备注">
          <el-input v-model="editItem.Remark" />
        </el-form-item>
        <el-form-item style="text-align:center">
          <el-button size="large" type="success" @click="validtAndSubmit">提交</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { _getAllDeliverChannel } from '@/api/baseInfo'
import request from '@/utils/request'

export default {
  name: 'ChannelMatchRules',
  data() {
    return {
      submiting: false,
      editMode: '',
      editItem: {
        Id: null,
        ChannelId: null,
        TargetChannelId: null,
        CustomerIdValues: [],
        CountryCodeValues: [],
        RuleNode: null,
        RuleType: null,
        MinWeight: null,
        MaxWeight: null,
        Enabled: false,
        Remark: null
      },
      showEditPannel: false,
      loading: false,
      channels: [],
      sourceData: [],
      types: [
        { Id: 1, Name: '指定渠道' },
        { Id: 2, Name: '客户指定' },
        { Id: 3, Name: '重量匹配' },
        { Id: 4, Name: '国家匹配' }
      ],
      nodes: [
        { Id: 1, Name: '下单' },
        { Id: 2, Name: '转单' },
        { Id: 3, Name: '重发' },
        { Id: 4, Name: '全部节点' }
      ],
      countries: [],
      customers: [],
      pagerDto: {
        _Eq_ChannelId: null,
        _Eq_TargetChannelId: null,
        _Eq_RuleNode: null,
        _Eq_RuleType: null,
        PageIndex: 1,
        PageSize: 100,
        total: 100
      },
      rules: {
        ChannelId: { required: true, message: '请选择渠道', trigger: 'blur' },
        TargetChannelId: {
          required: true,
          message: '请选择目标渠道',
          trigger: 'blur'
        },
        RuleNode: {
          required: true,
          message: '请选择规则节点',
          trigger: 'blur'
        },
        RuleType: {
          validator: this.checkRuleType,
          trigger: 'blur'
        }
      }
    }
  },
  created() {
    _getAllDeliverChannel().then((resp) => {
      this.channels = resp
    })
    this.getCountriesAndCustomers()
    this.pagerDto.PageIndex = 1
    this.pagerDto._Eq_ChannelId = ''
    this.getChannelMatchRules()
  },
  methods: {
    checkRuleType(rule, value, callback) {
      if (!value) {
        callback(new Error('必须选择规则类型'))
      }

      if (value == 1) {
        if (
          this.editItem.CountryCodeValues &&
          this.editItem.CountryCodeValues.length > 0
        ) {
          callback(new Error('类型为指定渠道时，不能选择国家'))
        } else if (
          this.editItem.CustomerIdValues &&
          this.editItem.CustomerIdValues.length > 0
        ) {
          callback(new Error('类型为指定渠道时，不能选择客户'))
        } else if (!!this.editItem.MinWeight || !!this.editItem.MaxWeight) {
          callback(new Error('类型为指定渠道时，不能设置重量'))
        }
      } else if (value == 2) {
        if (
          !this.editItem.CustomerIdValues ||
          this.editItem.CustomerIdValues.length <= 0
        ) {
          callback(new Error('类型为客户指定时，必须选择客户'))
        } else if (
          this.editItem.CountryCodeValues &&
          this.editItem.CountryCodeValues.length > 0
        ) {
          callback(new Error('类型为客户指定时，不能选择国家'))
        } else if (!!this.editItem.MinWeight || !!this.editItem.MaxWeight) {
          callback(new Error('类型为客户指定时，不能设置重量'))
        }
      } else if (value == 3) {
        if (!this.editItem.MinWeight && !this.editItem.MaxWeight) {
          callback(new Error('类型为重量匹配时，必须设置重量'))
        } else if (
          !!this.editItem.MinWeight &&
          isNaN(parseInt(this.editItem.MinWeight))
        ) {
          callback(new Error('最小重量必须为数字'))
        } else if (
          !!this.editItem.MaxWeight &&
          isNaN(parseInt(this.editItem.MaxWeight))
        ) {
          callback(new Error('最大重量必须为数字'))
        } else if (
          this.editItem.CountryCodeValues &&
          this.editItem.CountryCodeValues.length > 0
        ) {
          callback(new Error('类型为重量匹配时，不能选择国家'))
        } else if (
          this.editItem.CustomerIdValues &&
          this.editItem.CustomerIdValues.length > 0
        ) {
          callback(new Error('类型为重量匹配时，不能选择客户'))
        }
      } else if (value == 4) {
        if (
          !this.editItem.CountryCodeValues ||
          this.editItem.CountryCodeValues.length <= 0
        ) {
          callback(new Error('类型为国家匹配时，必须选择国家'))
        } else if (
          this.editItem.CustomerIdValues &&
          this.editItem.CustomerIdValues.length > 0
        ) {
          callback(new Error('类型为国家匹配时，不能选择客户'))
        } else if (!!this.editItem.MinWeight || !!this.editItem.MaxWeight) {
          callback(new Error('类型为国家匹配时，不能设置重量'))
        }
      }

      callback()
    },
    validtAndSubmit() {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          this.submit()
        } else {
          return false
        }
      })
    },
    edit(item) {
      this.editMode = 'edit'
      this.showEditPannel = true
      this.editItem.Id = item.Id
      this.editItem.ChannelId = item.ChannelId
      this.editItem.TargetChannelId = item.TargetChannelId
      this.editItem.CustomerIdValues = item.CustomerIdValues
      this.editItem.CountryCodeValues = item.CountryCodeValues
      this.editItem.RuleNode = item.RuleNode
      this.editItem.RuleType = item.RuleType
      this.editItem.MinWeight = item.MinWeight
      this.editItem.MaxWeight = item.MaxWeight
      this.editItem.Enabled = item.Enabled
      this.editItem.Remark = item.Remark
    },
    remove(item) {
      this.$confirm('是否删除该匹配规则?', '正在删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        request({
          url: '/channelMatchRules/remove',
          params: { id: item.Id },
          method: 'post'
        })
          .then((resp) => {
            console.log(resp)
            if (resp === true) {
              const idx = this.sourceData.findIndex((i) => i.Id === item.Id)
              this.sourceData.splice(idx, 1)
            } else {
              const msg = resp.message
              this.$message(msg)
            }
          })
          .catch(() => {
            this.$message('删除出错')
          })
          .finally(() => {
            this.loading = false
          })
      })
    },
    submit() {
      let url = '/channelMatchRules/create'
      let op = '新增'
      if (this.editMode === 'edit') {
        url = '/channelMatchRules/modify'
        op = '修改'
      }
      this.submiting = true
      request({
        url: url,
        data: this.editItem,
        method: 'post'
      })
        .then((resp) => {
          if (resp.success === true) {
            this.showEditPannel = false
            this.initEditItem()
            this.$alert(`${op}成功`, `${op}成功`, {
              confirmButtonText: '确定',
              callback: () => {
                this.getChannelMatchRules()
              }
            })
          } else {
            const msg = resp.message
            this.$message(msg)
          }
        })
        .finally(() => {
          this.submiting = false
        })
    },
    showAddPanel() {
      this.editMode = 'add'
      this.initEditItem()
      this.showEditPannel = true
    },
    initEditItem() {
      this.showEditPannel = false
      this.editItem.ChannelId = null
      this.editItem.Id = null
      this.editItem.TargetChannelId = null
      this.editItem.CustomerIdValues = null
      this.editItem.CountryCodeValues = null
      this.editItem.RuleNode = null
      this.editItem.RuleType = null
      this.editItem.MinWeight = null
      this.editItem.MaxWeight = null
      this.editItem.Enabled = null
      this.editItem.Remark = null
    },
    pagerSerach() {
      this.pagerDto.PageIndex = 1
      this.getChannelMatchRules()
    },
    getCountriesAndCustomers() {
      request({
        url: '/channelMatchRules/CountriesAndCustomers',
        method: 'get'
      }).then((resp) => {
        this.customers = resp.Customers
        this.countries = resp.Countries
      })
    },
    getChannelMatchRules() {
      this.loading = true
      request({
        url: '/channelMatchRules/query',
        method: 'post',
        data: this.pagerDto
      })
        .then((resp) => {
          this.loading = false
          this.pagerDto.total = resp.TotalCount
          this.pagerDto.PageIndex = resp.PageIndex

          this.sourceData = resp.Result
        })
        .finally(() => {
          this.loading = false
        })
    }
  }
}
</script>
