<template>
  <div class="component-set-freight">
    <el-dialog
      v-model="show"
      class="custom-edit-indent-info-dialog"
      title="设置运费参数"
      width="800px"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :append-to-body="true"
      :before-close="close"
    >
      <el-form
        ref="freightForm"
        label-width="140px"
        :rules="rules"
        :model="form"
        :inline="true"
      >
        <el-tabs
          v-model="activeTab"
          type="card"
        >
          <el-tab-pane
            label="基础参数"
            name="1"
          >
            <div class="flex flex-wrap tab-panel-1">
              <el-form-item
                label="汇率(RMB/AUD)"
                prop="rate_rmb_aud"
              >
                <el-input v-model="form.rate_rmb_aud"></el-input>
              </el-form-item>
              <el-form-item
                label="国内运费单价(重货)"
                prop="cn_price_heavy"
              >
                <div class="flex items-center">
                  <el-input
                    v-model="form.cn_price_heavy"
                    class="flex-auto"
                  ></el-input>
                  <div style="width: 60px; padding-left: 8px">(RMB)</div>
                </div>
              </el-form-item>
              <el-form-item
                label="税率(%)"
                prop="rate_tax"
              >
                <el-input v-model="form.rate_tax"></el-input>
              </el-form-item>
              <el-form-item
                label="国内运费单价(轻货)"
                prop="cn_price"
              >
                <div class="flex items-center">
                  <el-input
                    v-model="form.cn_price"
                    class="flex-auto"
                  ></el-input>
                  <div style="width: 60px; padding-left: 8px">(RMB)</div>
                </div>
              </el-form-item>
              <el-form-item
                label="燃油附加(%)"
                prop="rate_fuel"
              >
                <el-input v-model="form.rate_fuel"></el-input>
              </el-form-item>
              <el-form-item
                label="空+派燃油附加(%)"
                prop="rate_fuelplus"
              >
                <el-input v-model="form.rate_fuelplus"></el-input>
              </el-form-item>
              <el-form-item
                label="体积浮动(%)"
                prop="rate_bulk"
              >
                <el-input v-model="form.rate_bulk"></el-input>
              </el-form-item>
              <el-form-item
                label="海运费(AUD)"
                prop="sea_fee"
              >
                <el-input v-model="form.sea_fee"></el-input>
              </el-form-item>
              <el-form-item
                label="重量浮动(%)"
                prop="rate_weight"
              >
                <el-input v-model="form.rate_weight"></el-input>
              </el-form-item>
            </div>
          </el-tab-pane>
          <el-tab-pane
            label="航空运费单价"
            name="2"
          >
            <div class="flex items-start tab-panel-2">
              <div style="width: 120px">
                <el-tabs
                  v-model="currentAirTab"
                  tab-position="left"
                >
                  <el-tab-pane
                    name="dhl"
                    label="DHL"
                  ></el-tab-pane>
                  <el-tab-pane
                    name="tnt"
                    label="TNT"
                  ></el-tab-pane>
                  <el-tab-pane
                    name="fedex"
                    label="Fedex"
                  ></el-tab-pane>
                </el-tabs>
              </div>
              <div class="flex-auto">
                <el-table
                  :header-cell-style="{ backgroundColor: '#F2F6FC' }"
                  :data="computedAirForm"
                  stripe
                  border
                >
                  <el-table-column label="重量(KG)">
                    <template #default="scope">
                      <div class="flex items-center">
                        <el-form-item
                          style="width: 130px"
                          :rules="{
                            validator: checkInput,
                          }"
                          :prop="
                            computedAirFormRuleKey + '.' + scope.$index + '.min'
                          "
                        >
                          <el-input v-model="scope.row.min"></el-input>
                        </el-form-item>
                        <span style="margin-right: 10px">~</span>
                        <el-form-item
                          style="width: 130px"
                          :rules="{
                            validator: checkInput,
                          }"
                          :prop="
                            computedAirFormRuleKey + '.' + scope.$index + '.max'
                          "
                        >
                          <el-input v-model="scope.row.max"></el-input>
                        </el-form-item>
                      </div>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="单价(AUD/KG)"
                    width="200"
                  >
                    <template #default="scope">
                      <el-form-item
                        :rules="{
                          validator: checkInput,
                        }"
                        :prop="
                          computedAirFormRuleKey + '.' + scope.$index + '.price'
                        "
                      >
                        <el-input v-model="scope.row.price"></el-input>
                      </el-form-item>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="操作"
                    width="90"
                  >
                    <template #default="scope">
                      <el-form-item>
                        <el-button
                          size="small"
                          type="danger"
                          @click="deleteAir(scope.$index)"
                        >
                          {{ $t('btn_delete') }}
                        </el-button>
                      </el-form-item>
                    </template>
                  </el-table-column>
                </el-table>

                <br />
                <el-button
                  size="small"
                  @click="addAir"
                >
                  + 添加价格信息
                </el-button>
              </div>
            </div>
          </el-tab-pane>
          <el-tab-pane
            label="空+派单价"
            name="3"
          >
            <div class="tab-panel-3">
              <el-table
                :header-cell-style="{ backgroundColor: '#F2F6FC' }"
                :data="form.airplus"
                stripe
                border
              >
                <el-table-column label="重量(KG)">
                  <template #default="scope">
                    <div class="flex items-center">
                      <el-form-item
                        style="width: 130px"
                        :rules="{
                          validator: checkInput,
                        }"
                        :prop="'airplus.' + scope.$index + '.min'"
                      >
                        <el-input v-model="scope.row.min"></el-input>
                      </el-form-item>
                      <span style="margin-right: 10px">~</span>
                      <el-form-item
                        style="width: 130px"
                        :rules="{
                          validator: checkInput,
                        }"
                        :prop="'airplus.' + scope.$index + '.max'"
                      >
                        <el-input v-model="scope.row.max"></el-input>
                      </el-form-item>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  label="单价(AUD/KG)"
                  width="200"
                >
                  <template #default="scope">
                    <el-form-item
                      :rules="{
                        validator: checkInput,
                      }"
                      :prop="'airplus.' + scope.$index + '.price'"
                    >
                      <el-input v-model="scope.row.price"></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  width="90"
                >
                  <template #default="scope">
                    <el-form-item
                      label=""
                      prop=""
                    >
                      <el-button
                        size="small"
                        type="danger"
                        @click="deleteAirPlus(scope.$index)"
                      >
                        {{ $t('btn_delete') }}
                      </el-button>
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>

              <br />
              <el-button
                size="small"
                @click="addAirPlus()"
              >
                + 添加价格信息
              </el-button>
            </div>
          </el-tab-pane>
          <el-tab-pane
            label="海运运费信息"
            name="4"
          >
            <div class="tab-panel-4">
              <el-table
                :header-cell-style="{ backgroundColor: '#F2F6FC' }"
                :data="form.cbm"
                stripe
                border
              >
                <el-table-column label="CBM">
                  <template #default="scope">
                    <div class="flex items-center">
                      <el-form-item
                        style="width: 130px"
                        label=""
                        prop=""
                      >
                        <el-input v-model="scope.row.min"></el-input>
                      </el-form-item>
                      <span style="margin-right: 10px">~</span>
                      <el-form-item
                        style="width: 130px"
                        label=""
                        prop=""
                      >
                        <el-input v-model="scope.row.max"></el-input>
                      </el-form-item>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column
                  label="单价(AUD/KG)"
                  width="200"
                >
                  <template #default="scope">
                    <el-form-item
                      label=""
                      prop=""
                    >
                      <el-input v-model="scope.row.price"></el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column
                  label="操作"
                  width="90"
                >
                  <template #default="scope">
                    <el-form-item
                      label=""
                      prop=""
                    >
                      <el-button
                        size="small"
                        type="danger"
                        @click="deleteCBM(scope.$index)"
                      >
                        {{ $t('btn_delete') }}
                      </el-button>
                    </el-form-item>
                  </template>
                </el-table-column>
              </el-table>

              <br />
              <el-button
                size="small"
                @click="addCBM()"
              >
                + 添加价格信息
              </el-button>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
      <template #footer>
        <div class="flex justify-center items-center">
          <el-button
            type="primary"
            size="small"
            @click="checkForm(freightForm)"
          >
            {{ $t('btn_save') }}
          </el-button>
          <!-- <el-button
          @click="close"
          type=""
          size="small">
          关闭
        </el-button> -->
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { defineComponent, ref, watch, computed } from 'vue'
import {
  ElTabPane,
  ElTabs,
  ElButton,
  ElForm,
  ElFormItem,
  ElInput,
  ElTable,
  ElTableColumn,
  ElDialog,
  ElNotification,
  ElMessage,
} from 'element-plus'
import type { FormInstance } from 'element-plus'
import debounce from 'lodash.debounce'
import { $t } from '@/i18n/index'
import { getSettingDetail, saveSetting } from '@/api/indent'
defineComponent({
  name: 'EditInfo',
})
const { visible = false } = defineProps<{ visible: boolean }>()
const $emit = defineEmits(['update:visible', 'save'])

const activeTab = ref('1')
// 航空运费单价的3个子tab dhl tnt fedex
const currentAirTab = ref('dhl')
const show = ref(false)

const messageError = debounce(function (info) {
  ElMessage.error(info)
}, 300)
const checkInput = (rule: any, value: any, cb: any) => {
  if (!Number.isNaN(Number(value))) {
    cb()
  } else {
    messageError('请检查输入')
    cb(new Error('只能输入数字'))
  }
}
const rules = {
  rate_rmb_aud: [{ trigger: 'change', validator: checkInput }],
  cn_price_heavy: [{ trigger: 'change', validator: checkInput }],
  rate_tax: [{ trigger: 'change', validator: checkInput }],
  cn_price: [{ trigger: 'change', validator: checkInput }],
  rate_fuel: [{ trigger: 'change', validator: checkInput }],
  rate_fuelplus: [{ trigger: 'change', validator: checkInput }],
  rate_bulk: [{ trigger: 'change', validator: checkInput }],
  sea_fee: [{ trigger: 'change', validator: checkInput }],
}
const form = ref({
  // 基础参数 start
  rate_rmb_aud: '',
  cn_price_heavy: '',
  rate_tax: '',
  cn_price: '',
  rate_fuel: '',
  rate_fuelplus: '',
  rate_bulk: '',
  sea_fee: '',
  // 基础参数 end
  // 航空运费单价
  dhl_airline: [],
  tnt_airline: [],
  fedex_airline: [],
  // 空+派单价
  airplus: [],
  // 海运运费信息
  cbm: [],
}) as any

const getDetail = () => {
  getSettingDetail().then((response: any) => {
    if (response.code === 1) {
      form.value = Object.assign({}, response.result)

      form.value.dhl_airline = JSON.parse(form.value.dhl_airline)
      if (!Array.isArray(form.value.dhl_airline)) {
        form.value.dhl_airline = []
      }

      form.value.tnt_airline = JSON.parse(form.value.tnt_airline)
      if (!Array.isArray(form.value.tnt_airline)) {
        form.value.tnt_airline = []
      }

      form.value.fedex_airline = JSON.parse(form.value.fedex_airline)
      if (!Array.isArray(form.value.fedex_airline)) {
        form.value.fedex_airline = []
      }

      form.value.airplus = JSON.parse(form.value.airplus)
      if (!Array.isArray(form.value.airplus)) {
        form.value.airplus = []
      }

      form.value.cbm = JSON.parse(form.value.cbm)
      if (!Array.isArray(form.value.cbm)) {
        form.value.cbm = []
      }
      delete form.value.admin_id
      delete form.value.id
      delete form.value.is_del
      delete form.value.update_time
    }
  })
}

watch(
  () => visible,
  () => {
    show.value = visible
    if (show.value) getDetail()
  },
)

const computedAirFormRuleKey = computed(() => {
  let result = ''
  switch (currentAirTab.value) {
    case 'dhl':
      result = 'dhl_airline'
      break
    case 'tnt':
      result = 'tnt_airline'
      break
    case 'fedex':
      result = 'fedex_airline'
      break
  }
  return result
})
const computedAirForm = computed(() => {
  let result = []
  switch (currentAirTab.value) {
    case 'dhl':
      result = form.value.dhl_airline
      break
    case 'tnt':
      result = form.value.tnt_airline
      break
    case 'fedex':
      result = form.value.fedex_airline
      break
  }
  return result
})

const deleteCBM = (index: number) => {
  form.value.cbm.splice(index, 1)
}
const addCBM = () => {
  form.value.cbm.push({
    min: '',
    max: '',
    price: '',
  })
}
const deleteAirPlus = (index: number) => {
  form.value.airplus.splice(index, 1)
}
const addAirPlus = () => {
  form.value.airplus.push({
    min: '',
    max: '',
    price: '',
  })
}
const deleteAir = (index: number) => {
  switch (currentAirTab.value) {
    case 'dhl':
      form.value.dhl_airline.splice(index, 1)
      break
    case 'tnt':
      form.value.tnt_airline.splice(index, 1)
      break
    case 'fedex':
      form.value.fedex_airline.splice(index, 1)
      break
  }
}
const addAir = () => {
  computedAirForm.value.push({
    min: '',
    max: '',
    price: '',
  })
}
const freightForm = ref<FormInstance>()
const checkForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate((valid: boolean) => {
    // console.log(valid, 'valid')
    if (!valid) return
    saveSetting(form.value).then((response: any) => {
      if (response.code === 1) {
        ElNotification({
          title: '保存成功',
          message: '保存成功',
          duration: 3000,
        })
        $emit('save')
      }
    })
  })
}
const close = (done = {} as any) => {
  $emit('update:visible', false)
  if (typeof done === 'function') done()
}
</script>
<style lang="scss">
.component-set-freight {
  .el-dialog__body {
    min-height: 60vh;
    max-height: 72vh;
    overflow-y: scroll;
    overflow-x: auto;
    padding-top: 8px;
  }
}
</style>
<style lang="scss" scoped>
.tab-panel-1 {
  .el-form-item {
    width: 42%;
    &:nth-of-type(2n) {
      width: 48%;
    }
  }
}
.tab-panel-2,
.tab-panel-3,
.tab-panel-4 {
  width: 100%;
  position: relative;
  .el-form-item {
    margin-bottom: 0;
  }
}
</style>
