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

      <el-form-item :label="$t('适用商品')" prop="idList">
        <products-selector ref="productsSelector" :defaultIds="form.idList" v-model="form.idList" show-all @setall="toggleAll" />
      </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="requirements">
        <el-checkbox :true-label="1" :false-label="0"   v-model="form.requirements">{{$t('证书要求（支持多证书）')}}</el-checkbox>
      </el-form-item>
      <el-form-item :label="$t('订单方数上限')" prop="square">
        <el-input v-model="form.square" placeholder="" class="w-200"></el-input>
      </el-form-item>
      <el-form-item :label="$t('包装要求')" prop="packaging">
        <dict-selector :type="DICT_TYPE.ECW_PACKAGING_TYPE" v-model="form.packaging" />
      </el-form-item>
      <el-form-item :label="$t('是否预约入仓')" prop="needBook">
        <dict-selector form-type="radio" :type="DICT_TYPE.ECW_YESNO" v-model="form.needBook" formatter="number" />
      </el-form-item>
      <el-form-item :label="$t('每日入仓上限')" prop="dayLimit" v-if="form.needBook">
        <el-input placeholder="" v-model="form.dayLimit" class="w-200">
          <template slot="suffix">{{$t('立方米')}}</template>
        </el-input>
      </el-form-item>
      <el-form-item :label="$t('商品特性')" prop="attrId">
        <!-- <dict-selector form-type="checkbox" :type="DICT_TYPE.ECW_ORDER_ATTR" v-model="form.attrId" multiple /> -->
        <el-checkbox-group v-model="attrIds">
          <el-checkbox v-for="item in attrList" :label="item.id" :key="item.id">{{$l(item, 'attrName')}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item :label="$t('商品材质')" prop="materialType">
        <dict-selector form-type="radio" :type="DICT_TYPE.ECW_PRODUCT_MATERIAL" v-model="form.materialType"  />
      </el-form-item>
      <packaging-type key-arr="priceStepClearanceList" v-model="form">
        <el-button @click="visible =  true; open = false;" type="text">选择空运模板</el-button>
      </packaging-type>
      <p v-if="lineNum">
           <span>
             复制模板线路价格：{{lineNum}}个
           </span>
         <span @click="toPriceManager(formCopv)" style="color: #0a84ff;cursor: pointer;">
             查看《#{{$l(formCopv,'title')}}#》路线价格
           </span>
        <el-button style="font-size: 12px;margin-left: 15px;color: red;" type="text" @click="form.priceStepClearanceList = [];lineNum = 0"  >清除路线</el-button>
      </p>
      <el-form-item>
        <el-button type="primary" @click="submitForm">{{$t('确定')}}</el-button>
        <el-button @click="$router.back()">{{$t('返回')}}</el-button>
        <el-button type="default" @click="reset">{{$t('重置')}}</el-button>
      </el-form-item>
    </el-form>
    <el-dialog :visible.sync="visible" >
      <product-dialog @copyLine="copyLine"></product-dialog>
    </el-dialog>
  </div>
</template>
<script>
import { batchUpdateProduct } from '@/api/ecw/product';
import { getProductAttrList } from "@/api/ecw/productAttr";
import CustomersSelector from '@/components/CustomersSelector'
import { getDictData } from '@/utils/dict'
import RoutersSelector from '@/components/RoutersSelector'
import ProductsSelector from '@/components/ProductsSelector'
import Editor from '@/components/Editor'
import Selector from '@/components/Selector/index'
import PackagingType from "@/views/ecw/channel/componrnts/packaging-type.vue";
import ProductDialog from "@/views/ecw/product/product-dialog.vue";
export default {
  name: "EcwProductattrEdit",
  components: {ProductDialog, PackagingType, CustomersSelector, RoutersSelector, ProductsSelector, Editor, Selector },
  data() {
    return {
      formCopv:{},
      lineNum:0,
      visible:false,
      // 遮罩层
      loading: true,
      attrList: [],
      attrIds:[],
      // 表单参数
      form: {
        "attrId": undefined,
        "containerLocation": undefined,
        "dayLimit": undefined,
        "idList": [],
        "isAllProduct": 0,
        "needBook": undefined,
        "packaging": undefined,
        "requirements": undefined,
        "square": undefined,
        "materialType": undefined,
        priceStepClearanceList:[],
        priceLineCount:undefined,
        isCopyProductPriceTemplate:false,
      },
      // 表单校验
      rules: {},
      // checked: [false, false, false, false, false, false, false, false]
    };
  },
  computed: {

  },
  watch: {
    /* 'form.idList'(val) {
      if (val.length > 0) {
        this.form.isAllProduct = 0
      } else {
        this.form.isAllProduct = 1
      }
    }, */
    attrIds(val){
      this.form.attrId = val.join(',')
    }
  },
  created() {
    this.reset()
    this.form.idList = this.$route.query && this.$route.query.ids ? [...this.$route.query.ids].map(item => { return Number(item) }) : []
    getProductAttrList().then(res => {
      this.attrList = res.data
    })
  },
  activated() {
    this.form.idList = this.$route.query && this.$route.query.ids ? [...this.$route.query.ids].map(item => { return Number(item) }) : []
    getProductAttrList().then(res => {
      this.attrList = res.data
    })
  },
  methods: {
    /**跳转价格管理 */
    toPriceManager(row) {
      /* localStorage.setItem('product', JSON.stringify(row));
      localStorage.setItem('typeList', JSON.stringify(this.typeList)); */
      this.$router.push({
        name: 'ProductPrice',
        query: {
          product_id: row.id,
          product_type: row.typeId,
          transportType:3
        }
      })
    },
    copyLine(val , bol){
      this.formCopv = val
      let copy = ()=>{
        this.form.airWeightLimit = val.airWeightLimit;
        val.priceStepClearanceList.forEach((item ,index) =>{
          if(this.form.priceStepClearanceList[index]){
            this.form.priceStepClearanceList[index].clearancePrice = item.clearancePrice
            this.form.priceStepClearanceList[index].clearancePriceUnit = item.clearancePriceUnit
            this.form.priceStepClearanceList[index].clearanceVolumeUnit = item.clearanceVolumeUnit
            this.form.priceStepClearanceList[index].endNum = item.endNum
            this.form.priceStepClearanceList[index].startNum = item.startNum
            this.form.priceStepClearanceList[index].weightUnit = item.weightUnit
          }else {
            let p = {
              "channelId":'',
              "clearancePrice":item.clearancePrice,
              "clearancePriceUnit":item.clearancePriceUnit,
              "clearanceVolumeUnit":item.clearanceVolumeUnit,
              "endNum":item.endNum,
              "packagingId":'',
              "startNum":item.startNum,
              "weightUnit":item.weightUnit
            }
            this.form.priceStepClearanceList.push(p)
          }
        })
      }
      this.visible = false;
      if(bol){
        let message = this.$l(this.form,'title') ? `请确认是否要将#${this.$l(val,'title')}#的所有路线价格复制到当前商品#${this.$l(this.form,'title')}#中？` : `请确认是否要将#${this.$l(val,'title')}#的所有路线价格复制到当前商品中？`
        this.$confirm(message, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.form.priceLineCount = val.id;
          this.lineNum = val.priceLineCount;
          this.form.productTemplateId = val.id;
          this.isCopyProductPriceTemplate = true;
          copy()
          this.open = true;
        }).catch(() => {
          this.open = true;
        });
      }else {
        this.open = true;
        copy()
      }
      this.$forceUpdate()
    },
    toggleAll(e){
      this.$set(this.form, 'isAllProduct', e ? 1 : 0)
    },
    /** 表单重置 */
    reset() {
      this.form = {
        "attrId": undefined,
        "containerLocation": undefined,
        "dayLimit": undefined,
        "idList": [],
        "isAllProduct": 0,
        "needBook": undefined,
        "packaging": undefined,
        "requirements": 0,
        "square": undefined,
        "materialType": undefined,
        priceStepClearanceList:[],
        priceLineCount:undefined,
        isCopyProductPriceTemplate:false,

      };
      this.attrIds = []
      this.resetForm("form");
      this.lineNum = 0;
      this.$refs.productsSelector.empty()
    },
    verify(row){
      return (row.startNum !== '' && row.endNum !== '' && row.clearancePrice !== '' && row.clearancePriceUnit !== '' && row.clearanceVolumeUnit !== '')
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (!valid) {
          return;
        }
        let data = Object.assign({}, this.form)
        if(!data.isAllProduct && !data.idList.length){
          return this.$message(this.$t('请选择商品或勾选全部'))
        }
        if(!this.form.airWeightLimit){
          return this.$message.warning('请输入空运订单重量上限')
        }
        if(this.form.priceStepClearanceList.length === 0){
          return this.$message.warning('阶梯定价输入不完整！')
        }else {
          let bol = this.form.priceStepClearanceList.every(this.verify)
          if(!bol){
            return this.$message.warning('阶梯定价输入不完整！')
          }

        }
        batchUpdateProduct(data).then((response) => {
          this.$modal.msgSuccess(this.$t("修改成功"));
          this.reset()
          this.$forceUpdate()
          // this.$store.dispatch('tagsView/delCurrentView')
        });
      });
    },
  },
};
</script>
