<template>
  <div class="app-container">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px">

      <el-form-item label="商品类型" prop="typeId">
        <el-select v-model="form.productType" :disabled="!!$route.query.ids">
          <el-option v-for="type in productTypeList" :key="type.id" :label="type.titleZh" :value="type.id" />
        </el-select>
      </el-form-item>

      <el-form-item label="商品名称" prop="titleZh">
        <product-selector v-model="form.productId" :product-type="form.productType" @change="product = $event" :disabled="!!$route.query.ids" />
      </el-form-item>

      <el-form-item label="英文名称" prop="titleEn">
        <el-input :value="product ? product.titleEn : ''" disabled />
      </el-form-item>

      <!--单条路线修改-->
      <!-- <el-form-item label="路线" prop="lineChannelList" v-if="!$route.query.ids">
        <el-input
          v-for="item in lineList"
          :key="item.lineId"
          :value="'【' + getDictDataLabel(DICT_TYPE.ECW_TRANSPORT_TYPE, item.warehouseLineDO.transportType) + '】从【' + item.warehouseLineDO.startTitleZh + '】发往【' + item.warehouseLineDO.destTitleZh + '】'"
          disabled/>
      </el-form-item>--
      <!--多条路线批量修改-->
      <el-form-item label="路线" prop="lineChannelList" v-if="lineList.length">
        <template v-if="lineList.length == 1">
          <el-input
          v-for="item in lineList"
          :key="item.id"
          :value="!item.warehouseLineDO ? '数据异常,缺少warehouseLineDO字段' : '【' + getDictDataLabel(DICT_TYPE.ECW_TRANSPORT_TYPE, item.warehouseLineDO.transportType) + '】从【' + item.warehouseLineDO.startTitleZh + '】发往【' + item.warehouseLineDO.destTitleZh + '】'"
          disabled />
        </template>
        <el-checkbox-group v-else v-model="checkList">
          <el-checkbox
          v-for="item in lineList"
          :key="item.id"
          :label="item.id"
          :disabled="!item.warehouseLineDO"
          style="display:block"
          >
            {{
              !item.warehouseLineDO ? '数据异常,缺少warehouseLineDO字段' : 
              '【' + getDictDataLabel(DICT_TYPE.ECW_TRANSPORT_TYPE, item.warehouseLineDO.transportType) + '】从【' +
                item.warehouseLineDO.startTitleZh + '】发往【' + item.warehouseLineDO.destTitleZh + '】'
            }}
          </el-checkbox>
        </el-checkbox-group>
      </el-form-item>

      <routers-selector v-if="!$route.query.ids" v-model="selectedRoutes" />

      <el-card style="margin-bottom: 10px">
        <div slot="header" style="font-size:20px;">
          价格设置
        </div>
        <el-form-item label="默认运费" prop="transportPrice">
          <el-row :gutter="20">
            <el-col :span="4">
              <selector v-model="form.transportPriceUnit" :options="currencyList" label-field="titleZh" value-field="id" defaultable style="width:100px" />
            </el-col>

            <el-col :span="6">
              <inputor default="0" v-model.number="form.transportPrice" type="number" placeholder="整数或者两位小数" />
            </el-col>

            <el-col :span="4">
              /
              <selector v-model="form.transportVolumeUnit" :options="unitList" label-field="titleZh" value-field="id" defaultable style="width:100px" />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item label="默认清关费" prop="clearancePrice">
          <el-row :gutter="20">
            <el-col :span="4">
              <selector v-model="form.clearancePriceUnit" :options="currencyList" label-field="titleZh" value-field="id" defaultable style="width:100px" />
            </el-col>

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

            <el-col :span="4">
              /
              <selector v-model="form.clearanceVolumeUnit" :options="unitList" label-field="titleZh" value-field="id" defaultable style="width:100px" />
            </el-col>
          </el-row>
        </el-form-item>

        <!--特需-->
        <template v-for="(special, specialIndex) in this.specialProducts">
          <el-form-item
            :label="getDictDataLabel(DICT_TYPE.ECW_SPECIAL_REQ_FOR_LINE_PRODUCTS, special.specialDictType) + '运费'"
            :key="specialIndex + 'transport'">
            <el-row :gutter="20">
              <el-col :span="4">
                <selector v-model="special.transportPriceUnit" :options="currencyList" label-field="titleZh" value-field="id" defaultable style="width:100px" />
              </el-col>

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

              <el-col :span="4">
                / <selector v-model="special.transportVolumeUnit" :options="unitList" label-field="titleZh" value-field="id" defaultable style="width:100px" />
              </el-col>
            </el-row>
          </el-form-item>
          <el-form-item
            :label="getDictDataLabel(DICT_TYPE.ECW_SPECIAL_REQ_FOR_LINE_PRODUCTS, special.specialDictType) + '清关费'"
            :key="specialIndex + 'clearance'">
            <el-row :gutter="20">
              <el-col :span="4">
                <selector v-model="special.clearancePriceUnit" :options="currencyList" label-field="titleZh" value-field="id" defaultable style="width:100px" />
              </el-col>

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

              <el-col :span="4">
                / <selector v-model="special.clearanceVolumeUnit" :options="unitList" label-field="titleZh" value-field="id" defaultable style="width:100px" />
              </el-col>
            </el-row>
          </el-form-item>
        </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-card>


      <el-card>
        <div slot="header" style="font-size:20px;">
          基础信息
        </div>

        <el-form-item label="需要预约入仓" prop="needBook">
          <el-radio v-model.number="form.needBook" :label="1">是</el-radio>
          <el-radio v-model.number="form.needBook" :label="0">否</el-radio>
        </el-form-item>

        <el-form-item label="每日入仓上限" prop="dayLimit">
          <el-input v-model.number="form.dayLimit" type="number" style="width:100px" />立方米
        </el-form-item>

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

        <el-form-item label="方数要求" 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">确认提交</el-button>
      <el-button type="default" @click="$router.back">返回上一页</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 ProductSelector from '@/components/ProductSelector'
import { arrryToKeyedObjectBy } from '@/utils/index'
import Selector from '@/components/Selector'
import Inputor from '@/components/Inputor'

export default {
  components: { RoutersSelector, ProductSelector, Selector, Inputor },
  data() {
    return {
      checkList: [],
      selectedRoutes: [], // 勾选的路线渠道
      form: {},
      specialProducts: [],
      // specialList:[], // 特殊需求,默认四个
      rules: {
        /* typeId: [{ required: true, message: "产品类型不能为空", trigger: "blur" }],
        titleZh: [{ required: true, message: "产品名称不能为空", trigger: "blur" }],
        titleEn: [{ required: true, message: "英文名称不能为空", trigger: "blur" }], */
        transportPrice: [{ required: true, message: "海运费不能为空", trigger: "blur" }],
        clearancePrice: [{ required: true, message: "清关费不能为空", trigger: "blur" }],
        advanceStatus: [{ required: true, message: "是否预付不能为空", 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: [] //路线数组
    }
  },
  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() {
      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]
              }
            }
          }
        })
      }
    },
    selectedRoutes(routers) {
      routers.forEach(item => {
        item.shippingChannelId = item.channelId
      })
    }
  },
  async created() {
    // 修改回显
    if (this.$route.query.ids) {
      let query = {
        ids: this.$route.query.ids
      }
      getProductPriceList(query).then(res => {
        this.form = {
          productId: res.data[0].productId,
          productType: res.data[0].productType,
          specialList: res.data[0].specialList,
          advanceStatus: res.data[0].advanceStatus,
          needBook: res.data[0].needBook,
          dayLimit: res.data[0].dayLimit,
          containerLocation: res.data[0].containerLocation,
          square: res.data[0].square
        }
        this.lineList = res.data
      })
    }else{
      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)
        /* 
        getProduct(this.$route.query.product_id).then(res => {
          this.product = res.data
        }) */
      }
      
    }
    /* // 指定产品
    else 
    } */
    
    

    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: {
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }

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

        // 修改的提交
        if (this.$route.query.ids) {
          if(this.lineList.length == 1){
            data.lineChannelList = {
              lineId: this.lineList[0].warehouseLineId,
              shippingChannelId: this.lineList[0].shippingChannelId || 0
            }
          }else{
            data.lineChannelList = []
            this.lineList.forEach(item => {
              console.log(item.id, this.checkList.indexOf(item.id) > -1)
              if(this.checkList.indexOf(item.id) > -1){
                data.lineChannelList.push({
                    lineId: item.warehouseLineId,
                    shippingChannelId: item.shippingChannelId || 0
                  }
                )
              }
            })
          }
          if(data.lineChannelList.length < 1){
            return this.$message.error('请选择需要修改的路线')
          }
          data.productIdList = [this.form.productId]
          batchUpdateProductPrice(data).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.$router.replace('/product/product-price')
          })

          return;
        }
        // 添加的提交
        data.productId = this.product.id;
        data.lineChannelList = this.selectedRoutes
        createProductPrice(data).then(response => {
          this.$modal.msgSuccess("请求成功");
          this.$router.replace('/product/product-price')
        });
      });
    },
  }
}
</script>