<template>
  <div class="app-container">
    <div>
      <el-form inline>
        <el-button icon="el-icon-circle-plus-outline" type="success" @click="showAddPanel">新增规则明细</el-button>
      </el-form>
    </div>
    <el-table v-loading="loading" :data="details">
      <el-table-column prop="CountryNames" label="国家" width="200">
        <template slot-scope="scope">
          <el-link type="primary" @click="viewCountries(scope.row.CountryNames)">查看国家</el-link>
        </template>
      </el-table-column>

      <el-table-column label="最低重量（克）" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.MinWeight }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最高重量（克）" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.MaxWeight }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最低申报价值" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.MinDeclareValue }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最高申报价值" align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.MaxDeclareValue }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="DeclareCurrency" label="计算币种" align="center" />
      <el-table-column prop="DefaultUpRate" label="上调比例(%)" align="center" />
      <el-table-column prop="Enabled" label="是否启用">
        <template slot-scope="scope">
          <el-tag v-if="scope.row.Enabled" type="success">是</el-tag>
          <el-tag v-else type="danger">否</el-tag>
        </template>
      </el-table-column>
      <el-table-column width="200" label="操作">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="edit(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="remove(scope.row.Id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-dialog :visible.sync="showViewCountry" title="作用国家">
      <el-tag v-for="c in currentCountriesNames" :key="c" class="country-tag" style="margin: 5px">{{ c }}</el-tag>
    </el-dialog>
    <el-dialog :visible.sync="showEditPannel">
      <el-form ref="editForm" v-loading="submiting" label-width="10em" :model="editItem" :rules="rules">
        <el-form-item label="作用国家" prop="CountryCodes" class="country-codes">
          <el-select v-model="editItem.CountryCodesList" multiple filterable :collapse-tags="collapseChecked" @change="hanleChangeCountryChecked">
            <el-option
              v-for="item in countries"
              :key="item.Id"
              :label="`${item.CnName}(${item.Code})`"
              :value="item.Code"
            />
          </el-select>
          <div class="all-checked">
            <el-checkbox-button v-model="allCountryChecked" class="checked-button" @change="changeAllCountryChecked">全选</el-checkbox-button>
            <el-checkbox-button v-model="isAllCountryChecked" class="checked-button" @change="changeIsAllCountryChecked">取消选中</el-checkbox-button>
          </div>
        </el-form-item>
        <el-form-item label="作用客户">
          <el-select v-model="editItem.CustomerIdList" multiple 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="从重量" prop="MinWeight">
          <el-input-number v-model="editItem.MinWeight" />
        </el-form-item>

        <el-form-item label="到重量" prop="MaxWeight">
          <el-input-number v-model="editItem.MaxWeight" />
        </el-form-item>

        <el-form-item label="最低申报价值" prop="MinDeclareValue">
          <el-input-number v-model="editItem.MinDeclareValue" />
        </el-form-item>

        <el-form-item label="最高申报价值" prop="MaxDeclareValue">
          <el-input-number v-model="editItem.MaxDeclareValue" />
        </el-form-item>

        <el-form-item prop="DeclareCurrency" label="计算币种">
          <el-select v-model="editItem.DeclareCurrency" filterable>
            <el-option
              v-for="item in currencies"
              :key="item"
              :label="item"
              :value="item"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="默认上调比例(%)">
          <el-input v-model="editItem.DefaultUpRate" style="width: 201px;" />
        </el-form-item>

        <el-form-item label="是否启用" prop="Enabled">
          <el-switch 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 request from '@/utils/request'
import { _getCountries, _getCustomers } from '@/api/baseInfo'
import { _getCurrencies } from '@/api/financeRate'
export default {
  name: 'ChannelDeclareRuleDetail',
  data() {
    return {
      currentRuleId: 0,
      showEditPannel: false,
      loading: false,
      submiting: false,
      details: [],
      countries: [],
      customers: [],
      allCountryChecked: false,
      isAllCountryChecked: false,
      collapseChecked: false,
      editItem: {
        Id: 0,
        RuleId: 0,
        MinWeight: null,
        MaxWeight: null,
        MinDeclareValue: null,
        MaxDeclareValue: null,
        Enabled: true,
        CountryCodes: [],
        CountryCodesList: [],
        CustomerIdList: [],
        Remark: '',
        DeclareCurrency: 'USD',
        DefaultUpRate: undefined
      },
      currencies: [],
      showViewCountry: false,
      currentCountriesNames: [],
      rules: {
        CountryCodes: [
          {
            required: true,
            validator: this.validateCountry
          }
        ],
        CustomerIdList: [
          {
            required: true,
            validator: this.validateCustomer
          }
        ],
        MinWeight: [{ required: true, type: 'number', message: '请输入最小重量', trigger: 'blur' }],
        MaxWeight: [
          { required: true, type: 'number', message: '请输入最大重量', trigger: 'blur' },
          {
            validator: this.validateMaxWeight
          }
        ],
        MinDeclareValue: [
          { required: true, type: 'number', message: '请输入最低申报价值', trigger: 'blur' }
        ],
        MaxDeclareValue: [
          { required: true, type: 'number', message: '请输入最低申报价值', trigger: 'blur' }
        ],
        DeclareCurrency: [
          { required: true, message: '请选择计算币种', trigger: 'change' }
        ],
      }
    }
  },
  created() {
    const id = this.$route.query.Id
    this.currentRuleId = id
    _getCountries().then((resp) => {
      this.countries = resp

      this.getRuleDetails(id)
    })
    _getCustomers().then((res) => {
      this.customers = res
    })
    _getCurrencies().then((resp) => {
      this.currencies = resp
    })
  },
  methods: {
    initEditItem() {
      this.editItem.Id = 0
      this.editItem.RuleId = 0
      this.editItem.MinWeight = undefined
      this.editItem.MaxWeight = undefined
      this.editItem.MinDeclareValue = undefined
      this.editItem.MaxDeclareValue = undefined
      this.editItem.Enabled = true
      this.editItem.CountryCodes = []
      this.editItem.CountryCodesList = []
      this.editItem.CustomerIdList = []
      this.editItem.Remark = ''
      this.editItem.DeclareCurrency = 'USD'
      this.editItem.DefaultUpRate = undefined
      this.allCountryChecked = false
      this.isAllCountryChecked = false
    },
    showAddPanel() {
      this.editMode = 'add'
      this.initEditItem()

      this.showEditPannel = true
    },
    edit(item) {
      console.log(item)
      this.initEditItem()
      this.editItem.Id = item.Id
      this.editItem.RuleId = item.RuleId
      this.editItem.MinWeight = item.MinWeight == null ? undefined : item.MinWeight
      this.editItem.MaxWeight = item.MaxWeight == null ? undefined : item.MaxWeight
      this.editItem.MinDeclareValue = item.MinDeclareValue == null ? undefined : item.MinDeclareValue
      this.editItem.MaxDeclareValue = item.MaxDeclareValue == null ? undefined : item.MaxDeclareValue
      this.editItem.Enabled = item.Enabled
      this.editItem.CountryCodes = item.CountryCodes
      this.editItem.CountryCodesList = item.CountryCodesList
      this.editItem.CustomerIdList = item.CustomerIdList
      this.editItem.Remark = item.Remark
      this.editItem.DeclareCurrency = item.DeclareCurrency
      this.editItem.DefaultUpRate = item.DefaultUpRate
      this.initIsAllCountryChecked(item.CountryCodesList)
      this.editMode = 'edit'
      this.showEditPannel = true
    },
    remove(id) {
      this.$confirm('是否删除该明细?', '正在删除', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        request({
          url: '/ChannelDeclareRule/removeDetail',
          params: { id: id },
          method: 'post'
        })
          .then((resp) => {
            if (resp === true) {
              const idx = this.details.findIndex((i) => i.Id === id)
              this.details.splice(idx, 1)
            } else {
              const msg = resp.message
              this.$message(msg)
            }
          })
          .catch(() => {
            this.$message('删除出错')
          })
          .finally(() => {
            this.loading = false
          })
      })
    },
    submit() {
      let url = '/ChannelDeclareRule/CreateDetail'
      let op = '新增'
      if (this.editMode === 'edit') {
        url = '/ChannelDeclareRule/ModifyRuleDetail'
        op = '修改'
      }
      this.submiting = true
      this.editItem.RuleId = this.currentRuleId
      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.getRuleDetails(this.currentRuleId)
              }
            })
          } else {
            const msg = resp.message
            this.$message(msg)
          }
        })
        .finally(() => {
          this.submiting = false
        })
    },
    viewCountries(countryNames) {
      (this.showViewCountry = true), (this.currentCountriesNames = countryNames)
    },
    getRuleDetails(ruleId) {
      request({
        url: '/ChannelDeclareRule/GetDetailsByRuleId',
        params: { id: ruleId },
        method: 'post'
      })
        .then((resp) => {
          this.details = resp
        })
        .finally(() => {
          // this.loadingChannelNames = false;
        })
    },
    validtAndSubmit() {
      this.$refs['editForm'].validate((valid) => {
        if (valid) {
          this.submit()
        } else {
          return false
        }
      })
    },
    validateCountry(rule, value, callback) {
      if (!this.editItem.CountryCodesList || this.editItem.CountryCodesList.length <= 0) {
        callback(new Error('请选择国家'))
      } else {
        callback()
      }
    },
    validateCustomer(rule, value, callback) {
      if (!this.editItem.CustomerIdList || this.editItem.CustomerIdList.length <= 0) {
        callback(new Error('请选择客户'))
      } else {
        callback()
      }
    },
    validateMaxWeight(rule, value, callback) {
      if (value <= this.editItem.MinWeight) {
        callback(new Error('最大重量必须大于最大重量'))
      } else {
        callback()
      }
    },
    // 判断国家是否全选
    initIsAllCountryChecked(CountryCodesList) {
      this.allCountryChecked = this.countries.length === CountryCodesList.length
    },
    // 作用国家全选
    changeAllCountryChecked(val) {
      this.isAllCountryChecked = false
      this.collapseChecked = val
      if (val) {
        this.editItem.CountryCodesList = this.countries.map(item => item.Code)
        return false
      }
      this.changeIsAllCountryChecked()
    },
    // 取消作用国家全选
    changeIsAllCountryChecked() {
      this.allCountryChecked = false
      this.collapseChecked = false
      this.editItem.CountryCodesList = []
    },
    hanleChangeCountryChecked(val) {
      this.allCountryChecked = val.length === this.countries.length
    }
  }
}
</script>
<style scoped>
.title-lb {
  margin: 0 10px;
}

.country-tag {
  margin: 5px;
}

.country-codes {
  position: relative;
}
.country-codes .all-checked {
  position: absolute;
  top: 0;
  left: 201px;
  padding-left: 10px;
}
.country-codes .all-checked .checked-button {
  margin-right: 12px;
}
</style>
