<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="150px">
      <products-selector v-model="form.productIdList" class="mb-20" />

      <routers-selector v-model="selectedRoutes" />

      <el-card style="margin-bottom: 10px">
        <div slot="header" style="font-size:20px;">
          {{$t('价格设置')}}
          <span>
            <!-- <el-checkbox label="" @change="form.needPay=$event ? 1 : 0">{{$t('预付')}}</el-checkbox> -->
            <el-checkbox label="" @change="form.stepPrice=$event ? 1 : 0">{{$t('阶梯订单')}}</el-checkbox>
          </span>
        </div>
        <el-form-item :label="$t('预付')" prop="needPay" >
          <el-radio-group v-model="form.needPay">
            <el-radio :label="1">预付</el-radio>
            <el-radio :label="0">均可</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item :label="$t('单价模式')" prop="priceType">
          <dict-selector :type="DICT_TYPE.ECW_PRICE_TYPE" v-model="form.priceType" form-type="radio" />
        </el-form-item>
        <!--阶梯订单-->
        <template v-if="form.stepPrice==1" >
          <div v-for="(item, index) in priceStepList" :key="index">
            <div style="font-size:14px; margin:10px 0">
              {{$t('第{index}阶梯定价方案', {index: index+1})}}：
              <template v-if="index == priceStepList.length - 1">
                <el-link type="primary" @click.native="priceStepList.push({})">{{$t('添加区间')}}</el-link>
                <el-divider direction="vertical"></el-divider>
                <el-link type="danger" @click.native="priceStepList.splice(index, 1)">{{$t('删除')}}</el-link>
              </template>
            </div>
            <el-form-item :label="$t(`第{index}阶梯`, {index: index+1})">
              <el-input v-model="item.startNum" type="number" placeholder="" class="w100"></el-input>
              -
              <el-input v-model="item.endNum" type="number" placeholder="" class="w100"></el-input>
              /
              <selector v-model="form.weightUnit" :options="unitList" :label-field="$l('title')" value-field="id" defaultable2  class="w100" />
            </el-form-item>
            <el-form-item :label="$t('默认运费')" v-if="form.priceType != 1">
              <inputor default2="0" v-model.number="item.transportPrice" type="number" :placeholder="$t('整数或者两位小数')" class="w100 mr10" />
              <selector v-model="item.transportPriceUnit" :options="currencyList" :label-field="$l('title')" value-field="id" defaultable2  class="w100" />
              / <selector v-model="item.transportVolumeUnit" :options="unitList" :label-field="$l('title')" value-field="id" defaultable2  class="w100" />
            </el-form-item>
            <el-form-item :label="$t('默认清关费')" v-if="form.priceType != 1">
              <inputor default2="0" v-model.number="item.clearancePrice" type="number" :placeholder="$t('整数或者两位小数')" class="w100 mr10" />
              <selector v-model="item.clearancePriceUnit" :options="currencyList" :label-field="$l('title')" value-field="id" defaultable2  class="w100" />
              / <selector v-model="item.clearanceVolumeUnit" :options="unitList" :label-field="$l('title')" value-field="id" defaultable2  class="w100" />
            </el-form-item>

            <el-form-item :label="$t('默认全包价')" v-if="form.priceType == 1">
              <inputor default2="0" v-model.number="item.allPrice" type="number" :placeholder="$t('整数或者两位小数')" class="w100 mr10" />
              <selector v-model="item.allPriceUnit" :options="currencyList" :label-field="$l('title')" value-field="id" defaultable2  class="w100" />
              / <selector v-model="item.allVolumeUnit" :options="unitList" :label-field="$l('title')" value-field="id" defaultable2  class="w100" />
            </el-form-item>
          </div>
        </template>

        <template v-else>
          <el-form-item :label="$t('默认全包价')" v-if="form.priceType == 1">
            <inputor default2="0" v-model.number="form.allPrice" type="number" :placeholder="$t('整数或者两位小数')" class="w100 mr10" />
            <selector v-model="form.allPriceUnit" :options="currencyList" :label-field="$l('title')" value-field="id" defaultable2  class="w100" />
            / <selector v-model="form.allVolumeUnit" :options="unitList" :label-field="$l('title')" value-field="id" defaultable2  class="w100" />
          </el-form-item>
          <template v-else>
            <el-form-item :label="$t('默认运费')" prop="transportPrice">
              <el-row :gutter="20">
                <el-col :span="4">
                  <selector v-model="form.transportPriceUnit" :options="currencyList" :label-field="$l('title')" value-field="id" defaultable2 class="w-100" />
                </el-col>
                <el-col :span="6">
                  <inputor default2="0" v-model.number="form.transportPrice" type="number" :placeholder="$t('整数或者两位小数')" />
                </el-col>
                <el-col :span="4">
                  / <selector v-model="form.transportVolumeUnit" :options="unitList" :label-field="$l('title')" value-field="id" defaultable2 class="w-100" />
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item :label="$t('默认清关费')" prop="clearancePrice">
              <el-row :gutter="20">
                <el-col :span="4">
                  <selector v-model="form.clearancePriceUnit" :options="currencyList" :label-field="$l('title')" value-field="id" defaultable2 class="w-100" />
                </el-col>

                <el-col :span="6">
                  <inputor default2="0" v-model.number="form.clearancePrice" type="number" :placeholder="$t('整数或者两位小数')" />
                </el-col>

                <el-col :span="4">
                  /
                  <selector v-model="form.clearanceVolumeUnit" :options="unitList" :label-field="$l('title')" value-field="id" defaultable2 class="w-100" />
                </el-col>
              </el-row>
            </el-form-item>
          </template>


          <!--特需-->
          <template v-if="form.priceType==1">
            <el-form-item
              v-for="(special, specialIndex) in this.specialProducts"
              :label="getDictDataLabel(DICT_TYPE.ECW_SPECIAL_REQ_FOR_LINE_PRODUCTS, special.specialDictType) + $t('全包价')"
              :key="specialIndex + 'transport'">
              <el-row :gutter="20">
                <el-col :span="4">
                  <selector v-model="special.allPriceUnit" :options="currencyList" :label-field="$l('title')" value-field="id" defaultable2 class="w-100" />
                </el-col>

                <el-col :span="6">
                  <inputor default2="0" v-model.number="special.allPrice" type="number" :placeholder="$t('整数或者两位小数')" />
                </el-col>

                <el-col :span="4">
                  / <selector v-model="special.allVolumeUnit" :options="unitList" :label-field="$l('title')" value-field="id" defaultable2 class="w-100" />
                </el-col>
              </el-row>
            </el-form-item>
          </template>
          <template v-else v-for="(special, specialIndex) in this.specialProducts">
            <el-form-item
              :label="getDictDataLabel(DICT_TYPE.ECW_SPECIAL_REQ_FOR_LINE_PRODUCTS, special.specialDictType) + $t('运费')"
              :key="specialIndex + 'transport'">
              <el-row :gutter="20">
                <el-col :span="4">
                  <selector v-model="special.transportPriceUnit" :options="currencyList" :label-field="$l('title')" value-field="id" defaultable2 class="w-100" />
                </el-col>

                <el-col :span="6">
                  <inputor default2="0" v-model.number="special.transportPrice" type="number" :placeholder="$t('整数或者两位小数')" />
                </el-col>

                <el-col :span="4">
                  / <selector v-model="special.transportVolumeUnit" :options="unitList" :label-field="$l('title')" value-field="id" defaultable2 class="w-100" />
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item
              :label="getDictDataLabel(DICT_TYPE.ECW_SPECIAL_REQ_FOR_LINE_PRODUCTS, special.specialDictType) + $t('清关费')"
              :key="specialIndex + 'clearance'">
              <el-row :gutter="20">
                <el-col :span="4">
                  <selector v-model="special.clearancePriceUnit" :options="currencyList" :label-field="$l('title')" value-field="id" defaultable2 class="w-100" />
                </el-col>

                <el-col :span="6">
                  <inputor default2="0" v-model.number="special.clearancePrice" type="number" :placeholder="$t('整数或者两位小数')" />
                </el-col>

                <el-col :span="4">
                  / <selector v-model="special.clearanceVolumeUnit" :options="unitList" :label-field="$l('title')" value-field="id" defaultable2 class="w-100" />
                </el-col>
              </el-row>
            </el-form-item>
          </template>
        </template>

        <!-- <el-form-item label="是否预付" prop="advanceStatus">
          <dict-selector form-type="radio" :type="DICT_TYPE.ADVANCE_STATUS" v-model="form.advanceStatus" />
        </el-form-item> -->
        <el-form-item :label="$t('价格有效期')">
          <el-date-picker v-model="form.validateStartDate" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
          -
          <el-date-picker v-model="form.validateEndDate" value-format="yyyy-MM-dd HH:mm:ss"></el-date-picker>
        </el-form-item>
      </el-card>


      <el-card>
        <div slot="header" style="font-size:20px;">
          {{$t('基础信息')}}
        </div>

        <el-form-item :label="$t('是否预约入仓')" prop="needBook">
          <el-radio v-model.number="form.needBook" :label="1">{{$t('是')}}</el-radio>
          <el-radio v-model.number="form.needBook" :label="0">{{$t('否')}}</el-radio>
        </el-form-item>

        <el-form-item :label="$t('每日入仓上限')" prop="dayLimit" v-if="form.needBook == 1">
          <el-input v-model.number="form.dayLimit" type="number" class="w-100" />{{$t('立方米')}}
        </el-form-item>

        <el-form-item :label="$t('货柜位置')" prop="containerLocation">
          <dict-selector :type="DICT_TYPE.ECW_CONTAINER_LOCATION" v-model="form.containerLocation" />
        </el-form-item>

        <el-form-item :label="$t('订单方数上限')" prop="square">
          <el-input v-model.number="form.square" type="number" style="width:200px" />
        </el-form-item>
      </el-card>
    </el-form>

    <div style="margin: 20px 0">
      <el-button @click="submitForm" type="primary" :loading="loading">{{$t('确认提交')}}</el-button>
      <el-button type="default" @click="$router.back()">{{$t('返回上一页')}}</el-button>
    </div>
  </div>
</template>
<script>
import RoutersSelector from '@/components/RoutersSelector'
import { createProductPrice, updateProductPrice, batchUpdateProductPrice, deleteProductPrice, getProductPrice, getProductPriceList, getProductPricePage, exportProductPriceExcel } from "@/api/ecw/productPrice";
import { getProductType, getProductTypeList } from '@/api/ecw/productType'
import { getCurrencyList } from '@/api/ecw/currency';
import { getUnitList } from '@/api/ecw/unit';
import ProductsSelector from '@/components/ProductsSelector'
import { arrryToKeyedObjectBy } from '@/utils/index'
import Selector from '@/components/Selector'
import Inputor from '@/components/Inputor'
import { parseTime } from '@/utils/ruoyi'

export default {
  components: { RoutersSelector, ProductsSelector, Selector, Inputor },
  data() {
    return {
      checkList: [],
      selectedRoutes: [], // 勾选的路线渠道
      form: {
        // stepPrice: 0,
        // advanceStatus: 0,
        // needBook: 0,
        // dayLimit: 10000
      },
      specialProducts: [],
      priceStepList: [{},{}], // 阶梯价格
      // specialList:[], // 特殊需求,默认四个
      rules: {
        /* typeId: [{ required: true, message: "产品类型不能为空", trigger: "blur" }],
        titleZh: [{ required: true, message: "产品名称不能为空", trigger: "blur" }],
        titleEn: [{ required: true, message: "英文名称不能为空", trigger: "blur" }], */
        /* transportPrice: [{ required: true, message: this.$t("海运费不能为空"), trigger: "blur" }],
        clearancePrice: [{ required: true, message: this.$t("清关费不能为空"), trigger: "blur" }], */
        /* advanceStatus: [{ required: true, message: this.$t("是否预付不能为空"), trigger: "blur" }], */
        //containerLocation: [{ required: true, message: "货柜位置不能为空", trigger: "blur" }],
        //square: [{ required: true, message: "方数不能为空", trigger: "blur" }],
        // zhongLinjie:[{ required: true, message: "默认重货标准不能为空", trigger: "blur" }],
        // paoLinjie:[{ required: true, message: "默认泡货标准不能为空", trigger: "blur" }],
        // needBook: [{ required: true, message: "预约入仓不能为空", trigger: "blur" }],
      },
      product: null,
      /* productType: null, */
      currencyList: [],
      unitList: [],
      productTypeList: [],
      productDisabled: true,
      lineList: [], //路线数组
      loading: false
    }
  },
  computed: {

  },
  watch: {
    checkList() { //选择路线
      if (this.checkList.length > 0) {
        this.form.lineChannelList = this.checkList.map(item => {
          return { lineId: item, shippingChannelId: 0 }
        })
      } else {
        this.form.lineChannelList = []
      }
    },
    product() {
      this.$set(this.form, 'productType', this.product.typeId)
      /* getProductType(this.product.typeId).then(res => {
        this.productType = res.data
      }) */
    },
    form(val) {
      if (!val) return
      // 特殊需求回显
      if (val.specialList) {
        let keyed = arrryToKeyedObjectBy(val.specialList, 'specialDictType')
        this.specialProducts.map((item, index) => {
          if (keyed[item.specialDictType]) {
            for (let field in item) {
              if (keyed[item.specialDictType][field]) {
                item[field] = keyed[item.specialDictType][field]
              }
            }
          }
        })
      }
    },
    'form.transportVolumeUnit'(val){
      this.specialProducts.forEach(item => {
        item.transportVolumeUnit = val
      })
    },
    'form.clearanceVolumeUnit'(val){
      this.specialProducts.forEach(item => {
        item.clearanceVolumeUnit = val
      })
    },
    'form.allVolumeUnit'(val){
      this.specialProducts.forEach(item => {
        item.allVolumeUnit = val
      })
    },
    selectedRoutes(routers) {
      let transportIds = []
      routers.forEach(item => {
        item.shippingChannelId = item.channelId
        transportIds.push(+item.transportId)
      })

      // 如果只选择了空运（3），则默认体积单位改成千克
      transportIds = new Set(transportIds)
      console.log(transportIds)
      window.transportIds = transportIds
      if(transportIds.size == 1 && transportIds.has(3)){
        this.setDefaultVolumeUnit(6)
      }else this.setDefaultVolumeUnit(7)
    },
    'form.needBook'(val){
      if(val) this.$set(this.form, 'dayLimit', 10000)
      else delete this.form.dayLimit
    }
  },
  async created() {

      /* this.productDisabled = false

      // 获取类型列表
      getProductTypeList().then(res => this.productTypeList = res.data) */

      /* if (this.$route.query.product_type) {
        this.$set(this.form, 'productType', +this.$route.query.product_type)
      }
      if (this.$route.query.product_id) {
        this.$set(this.form, 'productId', +this.$route.query.product_id)
      }
 */
    // 默认今天起，两年有效
    /* this.form.validateStartDate = parseTime(Date.now())
    this.form.validateEndDate = parseTime(Date.now() + 86400*365*2*1000) */

    // 默认费用单位
    //this.setDefaultVolumeUnit(7)

    getCurrencyList().then(res => this.currencyList = res.data)
    getUnitList().then(res => this.unitList = res.data)

    this.getDictDatas(this.DICT_TYPE.ECW_SPECIAL_REQ_FOR_LINE_PRODUCTS).forEach(item => {
      this.specialProducts.push({
        "clearancePrice": null,
        "clearancePriceUnit": null,
        "clearanceVolumeUnit": null,
        "specialDictType": item.value,
        "transportPrice": null,
        "transportPriceUnit": null,
        "transportVolumeUnit": null,
      })
    })
  },
  methods: {
    setDefaultVolumeUnit(unit){
      this.$set(this.form, 'transportVolumeUnit', unit)
      this.$set(this.form, 'clearanceVolumeUnit', unit)
      this.$set(this.form, 'allVolumeUnit', unit)
    },
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }

        // 只有新增的时候做判断
        if (!this.$route.query.ids && (!this.selectedRoutes || !this.selectedRoutes.length)) {
          this.$message.error(this.$t('请选择线路'));
          return;
        }
        let data = Object.assign({}, this.form, {
          // lineChannelList: this.selectedRoutes,
          specialList: this.specialProducts,
          isAllProduct: this.form.productIdList.length == 0 ? 1 : 0
        })
        if(this.form.stepPrice == 1){
          data.priceStepList = this.priceStepList
        }

        data.lineChannelList = this.selectedRoutes

        if(data.lineChannelList.length < 1){
          return this.$message.error(this.$t('请选择需要修改的路线'))
        }
        this.loading = true
        batchUpdateProductPrice(data).then(response => {
          this.$modal.msgSuccess(this.$t("修改成功"));
          this.$router.replace('/lineProject/product-price?' + (new URLSearchParams(this.$route.query)).toString())
        })
        .finally(res => this.loading = false)
      });
    },
  }
}
</script>
<style scoped>
.w100{
  width: 100px;
}
.mr10{
  margin-right: 10px;
}
</style>
