<template>

  <div class="order-detail-wrapper">
    <bread-crumb :curmbFirst="curmbFirst" :curmbSecond="curmbSecond"></bread-crumb>
    <div class="order-detail-content screenSet" id="screenSet">
      <div class="header-title">店铺运费</div>
      <div class="freight-config-content">
        <el-form ref="form" :model="formData" label-width="100px" inline>
          <!-- ≤,≥,＜,＞ -->
          <el-row class="title">
            运费配置
          </el-row>
          <el-row
            class="c-row"
            :style="{ padding: index != 0 ? '20px' : '' }"
            v-for="(item, index) in formData.list.slice(0, 1)"
            :key="'first' + index"
          >
            <span v-if="index == 0" style="margin: 0 20px 0 40px;">0</span>
            <el-input
              v-else
              disabled
              v-model="item.rangeMin"
              size="small"
              style="width: 80px"
              placeholder="请输入"
            ></el-input>

            <span> ≤ </span>
            <span class="big">订单金额</span>
            <span> ＜ </span>
            <el-form-item :prop="`list.${index}.rangeMax`" :rules="bgRules">
              <el-input
                v-model="item.rangeMax"
                size="small"
                style="width: 80px;"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <span class="small">元</span>
            <span class="middle">运费：</span>
            <el-form-item :prop="`list.${index}.fee`" :rules="bgRules">
              <el-input
                v-model="item.fee"
                size="small"
                style="width: 80px"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <span class="small">元</span>
          </el-row>
          <el-row>
            <el-button
              style="margin: 10px 20px 20px;"
              size="small"
              type="primary"
              @click="addCondition"
            >添加条件
            </el-button>
          </el-row>
          <el-row
            class="c-row"
            style="padding: 10px 20px;"
            v-for="(item, index) in formData.list.slice(1)"
            :key="index"
          >
            <el-input
              v-model="item.rangeMin"
              disabled
              size="small"
              style="width: 80px"
              placeholder="请输入"
            ></el-input>
            <span> ≤ </span>
            <span class="big">订单金额</span>
            <span> ＜ </span>
            <el-form-item :prop="`list.${index}.rangeMax`" :rules="bgRules">
              <el-input
                v-model="item.rangeMax"
                size="small"
                style="width: 80px;"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <span class="small">元</span>
            <span class="middle">运费：</span>
            <el-form-item :prop="`list.${index}.fee`" :rules="bgRules">
              <el-input
                v-model="item.fee"
                size="small"
                style="width: 80px;"
                placeholder="请输入"
              ></el-input>
            </el-form-item>
            <span class="small">元</span>
            <el-button
              type="danger"
              size="small"
              @click="deleteCondition(index + 1)"
            >删除</el-button>
          </el-row>
          <el-row class="title" style="margin-top: 80px;">
            提示文案
          </el-row>
          <el-row>
            <el-form-item class="lh" label="运费说明：">
              <el-input
                v-model="formData.intro"
                size="small"
                maxlength="10"
                style="width: 410px"
                placeholder="请输入"></el-input>
            </el-form-item>
          </el-row>
        </el-form>
      </div>
      <div class="header-title">商品运费</div>
      <el-button
        style="margin: 10px 20px 20px;"
        size="small"
        type="primary"
        @click="addGoodsCondition"
      >添加条件
      </el-button>
      <el-table :data="resultForm.goodConditionReqList"  @row-click='handleRowClickRole' border class="item-table" style="width: 100%;margin-top: 30px;">
        <el-table-column prop="goodIds" label="商品ID" min-width="100" align="center">
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.goodIds" :key="index" style="text-align: center;margin: 0 auto;padding: 0;">
            <div v-if="index != scope.row.goodIds.length - 1" style="cursor: pointer;color: #449284;float: left;display: inline-block;" @click="viewGoods(item)">{{item}}、</div>
            <div v-else-if="index == scope.row.goodIds.length - 1" style="cursor: pointer;color: #449284;float: left;display: inline-block;" @click="viewGoods(item)">{{item}}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="conditionType" label="包邮条件" min-width="100" align="center">
          <template slot-scope="scope">
            <div v-if="scope.row.conditionType == 1">
              满{{scope.row.number}}件包邮
            </div>
            <div v-if="scope.row.conditionType == 2">
              满{{scope.row.numberText}}元包邮
            </div>
          </template>
        </el-table-column>

        <el-table-column prop="intro" label="说明" min-width="100" align="center">
        </el-table-column>
        <el-table-column prop="status" label="操作" min-width="100" align="center">
          <template slot-scope="scope">
          <el-button type="text" size="small" @click="editGoodsFreight(scope.row)">编辑</el-button>
          <el-button type="text" size="small" @click="delGoodsFreight(scope.row,scope.$index)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-row style="margin: 50px 0 0 220px;">
        <el-button
          :disabled="btnDisabled"
          type="primary"
          size="small"
          @click="beforSave()"
        >保存</el-button>
        <el-button
          :disabled="btnDisabled"
          size="small"
          @click="cancleSave()"
        >取消</el-button>
      </el-row>
      <el-dialog
        :title="title"
        :visible.sync="setAddVisible"
        width="60%">
        <!--            <el-row :gutter="30" class="row search" type="flex" style="margin-bottom:0;">-->
        <el-form ref="GoodsPriceForm"
                 :rules="addRules"
                 :model="goodCondition"
                 label-width="250px"
                 label-suffix=":"
                 label-position="right"
                 size="mini"
                 style="width: 100%;">

          <el-form-item label="适用商品ID" class="required-label" prop="goodIds">
            <el-col :span="12">
<!--              <el-select v-model="goodCondition.goodIdList"-->
<!--                         filterable-->
<!--                         remote-->
<!--                         reserve-keyword-->
<!--                         placeholder="多个商品ID，以“、”隔开"-->
<!--                         clearable-->
<!--                         value-key="id"-->
<!--                         style="width: 130%;"-->
<!--                         :remote-method="remoteMethod"-->
<!--                         @change="nameChange"-->
<!--                         @visible-change="noSelectHand">-->
              <el-select v-model="goodCondition.goodIds"
                         filterable
                         clearable
                         multiple
                         placeholder="可以选择多个商品ID"
                         style="width: 130%;">
                <el-option
                  v-for="item in nameList"
                  :key="item.id"
                  :label="item.id"
                  :value="item.id">
                  <span>{{item.value}}</span>
                </el-option>
              </el-select>
            </el-col>
          </el-form-item>

          <el-form-item label="包邮条件" class="required-label" prop="conditionType">
            <el-col :span="4">
              <el-select
                v-model="goodCondition.conditionType"
                size="small">
                <el-option
                  v-for="(item,index) in typeList"
                  :key="index"
                  :label="item.label"
                  :value="item.value"
                ></el-option>
              </el-select>
            </el-col>
            <el-col :span="9" style="margin-left: 5px;">
              <span style="margin-left: 5px;">满</span>
              <el-input-number v-if="goodCondition.conditionType == 1" v-model="goodCondition.number" style="margin-left: 5px;" size="small" :precision="0" :min="1" :max="100000"></el-input-number>
              <el-input-number v-if="goodCondition.conditionType == 2" v-model="goodCondition.number" style="margin-left: 5px;" size="small" :precision="2" :min="0.00" :max="99999.99"></el-input-number>
              <span style="margin-left: 5px;" v-if="goodCondition.conditionType == 1">件包邮</span>
              <span style="margin-left: 5px;" v-if="goodCondition.conditionType == 2">元包邮</span>
            </el-col>
          </el-form-item>
          <el-form-item label="运费说明" class="required-label">
            <el-col :span="15">
              <el-input v-model="goodCondition.intro" maxlength="10" style="width: 100%;" size="small" placeholder="请输入"></el-input>
            </el-col>
          </el-form-item>

        </el-form>
        <!--            </el-row>-->
        <span slot="footer" class="dialog-footer" style="text-align: center;">
                <el-button @click="setAddVisible = false">取 消</el-button>
                <el-button type="primary" @click="save()">保存</el-button>
            </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
let vm = null;
import BreadCrumb from "@/components/breadcrumb.vue";
import { getExpressFee, createOrModifyExpressFee, getFreightConfig, saveFreightConfig } from "@/utils/freight";
import {closeLoading, openLoading} from "../../utils/utils";
import { getGoodsIdList } from '@/utils/goods';
export default {
  components: {
    BreadCrumb
  },
  data() {
    var checkRange = (rule, value, callback) => {
      console.log("in checkRange", rule);
      let min = 0,
        max = 999999999.99;
      let arr = (value + "").split(".");
      if (arr.length > 1) {
        let temp = arr[1];
        if (temp.length > 2) {
          return callback(new Error("最多为2位小数"));
        }
      }
      let val = parseFloat(value);
      if (val >= min && val <= max) {
        callback();
      } else {
        callback(new Error(`输入范围0 ~ 999999999.99`));
      }
    };
    return {
      curmbFirst: '云鹊店铺',
      curmbSecond: '运费配置',
      btnDisabled: false,
      formData: {
        expressFeeConfigId: 0,
        intro: "",
        introId:"",
        list: [
          {
            fee: 0,
            rangeMin: 0,
            rangeMax: 0,
          },
        ],
      },
      model:{
        type:1,
        userName: "",
      },
      typeList: [
        {
          label: '件数',
          value: 1,
        }, {
          label: '金额',
          value: 2,
        }],
      title:"添加条件",
      setAddVisible: false,
      storeId:'',
      goodCondition:{
        goodIds:[],
        conditionType:'',
        number:'',
        intro:'',
        goodIdList:''
      },
      goodIdsArray:[],
      nameList:[],
      resultForm:{
        goodConditionReqList:[],
        intro:'',
        introId:'',
        storeExpressIntervalReqList:[],
        storeId:''
      },
      rowIndex:'',
      addRules:{
        goodIds: [
          {required: true, message: "请输入商品ID", trigger: 'blur'}
        ],
        conditionType: [
          {required: true, message: "请选择包邮条件", trigger: 'blur'}
        ],
      },
      bgRules: [{ validator: checkRange, trigger: "blur" }],
    };
  },
  watch: {
    "formData.list": {
      handler(val) {
        const length = val.length;
        if (length > 1) {
          for (let i = 1; i < length; i++) {
            val[i].rangeMin = val[i - 1].rangeMax;
          }
        }
      },
      deep: true,
    },
  },
  created() {
    vm = this;
    this.storeId = this.$route.query.storeId;
    // this.getExpressFeeInfo();
    this.getFreightConfig();
  },
  methods: {

    changeValue(v){
      console.log(v);
    },
    // 对数据进行处理
    dataHandler(listData, isRatioLower = true) {
      let list = JSON.parse(JSON.stringify(listData));
      let ratio = 0.01;
      if(isRatioLower) {
        list.map( item => {
          item.fee = Number(item.fee * ratio).toFixed(2);
          item.rangeMin = Number(item.rangeMin * ratio).toFixed(2);
          item.rangeMax = Number(item.rangeMax * ratio).toFixed(2);
        });
      } else {
        ratio = 100;
        list.map( item => {
          item.fee = parseInt(item.fee * ratio);
          item.rangeMin = parseInt(item.rangeMin * ratio);
          item.rangeMax = parseInt(item.rangeMax * ratio);
        });
      }
      return list;
    },

    // 获取配置信息
    getExpressFeeInfo() {
      getExpressFee().then( res => {
        let curData = res.data;
        if(res.data && res.data.list && res.data.list.length) {
          curData.list = this.dataHandler(res.data.list);
        } else {
          curData.list = this.formData.list;
        }
        this.formData = curData;
      })
    },

    // 增加单个条件
    addCondition() {
      this.formData.list.push({
        fee: 0,
        rangeMin: 0,
        rangeMax: 0,
      });
    },
    handleRowClickRole(row){
      this.rowIndex = row.index
      console.log(this.rowIndex)
    },
    // 删除条件
    deleteCondition(index) {
      this.formData.list.splice(index, 1);
    },

    // 保存前校验
    beforSave() {
      this.$refs["form"].validate((valid) => {
        if (!valid) return false;
        this.$confirm("是否确认保存?", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.saveAll();
          })
          .catch(() => {});
      });
    },

    // 保存
    saveAll() {
      this.btnDisabled = true;
      let formData = JSON.parse(JSON.stringify(this.formData));
      formData.list = this.dataHandler(formData.list, false);
      vm.resultForm.storeExpressIntervalReqList = formData.list;
      vm.resultForm.intro = formData.intro;
      vm.resultForm.introId = formData.introId;
      vm.resultForm.storeId = vm.storeId;
      saveFreightConfig(vm.resultForm)
      // createOrModifyExpressFee(formData)
        .then((res) => {
          if (res.code == "000000") {
            // this.getExpressFeeInfo();
            this.$message({ type: "success", message: "保存成功!" });
            this.$router.push({
              path: `/shop-list`
            })
          } else {
            this.$message({ type: "error", message: res.message });
          }
        })
        .finally((res) => {
          this.btnDisabled = false;
        });
    },
    cancleSave(){
      this.$router.push({
        path: `/shop-list`
      })
      // this.$confirm(`是否取消？`, "", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning"
      //   // customClass: 'range-make-box',
      // })
      //   .then(() => {
      //     //  confirm
      //     vm.DELETE("rtc/liveAdmin/" + row.id, {}).then(res => {
      //       if (res.code == "000000") {
      //         vm.$message({
      //           type: "success",
      //           message: "删除成功"
      //         });
      //         this.getLiveList("", "");
      //       } else {
      //         vm.$message({
      //           type: "warning",
      //           message: res.message
      //         });
      //       }
      //     });
      //   })
      //   .catch(() => {});
    },

    // 查看商品详情
    viewGoods(row){
      // url = `/create-good?id=${row.goodsId}&storeId=${this.searchForm.storeId}&goodsType=${goodsType}&commissionFlag=${this.commissionFlag}`
      let url = `/create-good?id=${row}&storeId=${this.storeId}&goodsType=5&commissionFlag=1`
    // this.$store.dispatch('goodsManage/changeGoodsInfo', {...row});
    this.$router.push({
      path: url
    })
    },
    addGoodsCondition(){
      vm.remoteMethod();
      vm.goodCondition = {
          goodIds:[],
          conditionType:'',
          number:'',
          intro:'',
          goodIdList:''
      };
      this.title = "添加条件";
      this.setAddVisible = true;

    },

    setIdArray(goodIdList){
      let idArray = [];
      if(goodIdList.indexOf("、") > -1){
        idArray = goodIdList.split("、");
      }
      else {
        idArray.push(goodIdList);
      }
      return idArray;

    },
    getIdArray(goodIds){
      let idArray = '';
      for(let i=0; i < goodIds.length; i++){
        if(i != goodIds.length - 1){
          idArray = idArray + goodIds[i] + "、";
        }
        else if(i == goodIds.length - 1){
          idArray = idArray + goodIds[i];
        }
      }
      return idArray;
    },

    editGoodsFreight(row){

      vm.remoteMethod();
      let idArray = this.getIdArray(row.goodIds);

      if(row.conditionType == 2){
        vm.goodCondition = {
          id:row.id,
          goodIds:row.goodIds,
          conditionType:row.conditionType,
          number:row.number/100,
          intro:row.intro,
          introId:row.introId,
          goodIdList:idArray
        };
      }
      else {
        vm.goodCondition = {
          id:row.id,
          goodIds:row.goodIds,
          conditionType:row.conditionType,
          number:row.number,
          intro:row.intro,
          introId:row.introId,
          goodIdList:idArray
        };
      }

      this.title = "修改条件";
      this.setAddVisible = true;
    },
    delGoodsFreight(row,index){
     // vm.rowIndex;
      vm.resultForm.goodConditionReqList.splice(index,1);
    },

    // 获取配置信息
    getFreightConfig() {

      getFreightConfig({id:this.storeId}).then( res => {
        let curData = res.data;
        if(res.data && res.data.expressFeeIntervalConfigList && res.data.expressFeeIntervalConfigList.length) {
          curData.list = this.dataHandler(res.data.expressFeeIntervalConfigList);
        } else {
          curData.list = this.formData.list;
        }

        if(res.data.goodConditionDtoList){
          for (let i=0;i < res.data.goodConditionDtoList.length; i++){

            if(res.data.goodConditionDtoList[i].goodExpressConditionConfig.conditionType == 2){
              this.resultForm.goodConditionReqList.push(
                 {id:res.data.goodConditionDtoList[i].goodExpressConditionConfig.id,
                  goodIds:res.data.goodConditionDtoList[i].goodIds,
                  conditionType:res.data.goodConditionDtoList[i].goodExpressConditionConfig.conditionType,
                  number:res.data.goodConditionDtoList[i].goodExpressConditionConfig.number,
                  numberText:res.data.goodConditionDtoList[i].goodExpressConditionConfig.number/100,
                  intro:res.data.goodConditionDtoList[i].goodExpressConditionConfig.intro,
                  introId:res.data.goodConditionDtoList[i].goodExpressConditionConfig.id
                });
            }
            else {
              this.resultForm.goodConditionReqList.push(
                 {id:res.data.goodConditionDtoList[i].goodExpressConditionConfig.id,
                  goodIds:res.data.goodConditionDtoList[i].goodIds,
                  conditionType:res.data.goodConditionDtoList[i].goodExpressConditionConfig.conditionType,
                  number:res.data.goodConditionDtoList[i].goodExpressConditionConfig.number,
                  numberText:res.data.goodConditionDtoList[i].goodExpressConditionConfig.number,
                  intro:res.data.goodConditionDtoList[i].goodExpressConditionConfig.intro,
                  introId:res.data.goodConditionDtoList[i].goodExpressConditionConfig.id
                });
            }

          }
        }
        // this.tableData = res.data.goodConditionDtoList;
        this.formData.list = curData.list;
        this.formData.intro = res.data.storeExpressFeeIntro.intro;
        this.formData.introId = res.data.storeExpressFeeIntro.id;
      })
    },

    remoteMethod(val) {
      this.searchForm = {
          goodsIdList:[],
          goodIdStr	:val,
          goodsType	:'',
          pageNo:1,
          pageSize:	10,
          storeId:this.storeId,
          commissionType: 0
      };
      // if (val.length >= 2) {
        // console.log('搜索',val)
        getGoodsIdList(this.searchForm)
        // this.GET(`/diagnose/commission/downDoctor/doctorInfoByNameLike?name=${val}`)
          .then(function (res) {
            if (res.code == '000000') {
              // let data = JSON.parse(JSON.stringify(res.data.data));//通过这个实现深拷贝
              let list = res.data.goodsList;
              vm.expertData = list;
              let newList = [];
              list.map((item, index) => {
                newList[index] = {
                  value: `${item.goodsId} ${item.goodsName}`,
                  id: item.goodsId,
                  name: item.goodsName,
                }
              })
              // console.log('新数组',newList)
              vm.nameList = newList;
            }
          }).catch(function (error) {
          errorResponseCheck(error, vm);
        });
      // }else {
      //   vm.expertData = [];
      //   vm.nameList = [];
      // }
    },
    nameChange(val) {
      // console.log('选中的值',val)
      let addFlag = true;
      if (val) {
        for(let i=0; i < vm.expertData.length; i++){
          if (val == vm.expertData[i].goodsId) {
            let item = vm.expertData[i];
            vm.goodIdsArray = vm.goodCondition.goodIds;
            for(let j=0; j < vm.goodIdsArray.length; j++){
              if(vm.goodIdsArray[j] == val){
                addFlag = false;
                break;
              }
            }
            if(addFlag){
              vm.goodIdsArray.push(val);
            }
            vm.goodCondition.goodIdList = this.getIdArray(vm.goodIdsArray);
            break;
            // vm.model.userName = item.name;
            // vm.model.mobile = item.mobilePhone;
            // vm.model.hospitalName = item.hospital;
            // vm.model.department = item.department;
            // vm.model.title = item.title;
            // vm.model.userId = item.doctorId;
          }
        }
      }else {
        vm.goodCondition.goodIdList = "";
      }
      vm.nameList = [];
    },
    noSelectHand(val) {
      if (!val && !vm.goodCondition.goodIdList) {
        vm.nameList = [];
      }
    },
    // 保存商品运费添加条件
    save(){
      let addFlag = false;
      this.$refs["GoodsPriceForm"].validate((valid) => {
        if (!valid) return false;
        // vm.goodCondition.goodIds = [];
        // vm.goodCondition.goodIds = vm.setIdArray(vm.goodCondition.goodIdList);

        if(vm.resultForm.goodConditionReqList.length > 0){
          // this.formData.tabs[0].contents = vm.resultForm.goodConditionReqList.filter(function (item) {
          //   return item.goodIds == vm.goodCondition.goodIds;
          // });
          for(let i=0; i < vm.resultForm.goodConditionReqList.length; i++){
            if((vm.goodCondition.id != ""
              && vm.resultForm.goodConditionReqList[i].id == vm.goodCondition.id)
            || (vm.goodCondition.id == "" && vm.getIdArray(vm.resultForm.goodConditionReqList[i].goodIds) == vm.getIdArray(vm.goodCondition.goodIds))){
              vm.resultForm.goodConditionReqList[i].conditionType = vm.goodCondition.conditionType;
              vm.resultForm.goodConditionReqList[i].goodIds = vm.goodCondition.goodIds;
              if(vm.goodCondition.conditionType == 2){
                vm.resultForm.goodConditionReqList[i].number = vm.goodCondition.number * 100;
                vm.resultForm.goodConditionReqList[i].numberText = vm.goodCondition.number;
              }
              else{
                vm.resultForm.goodConditionReqList[i].number = vm.goodCondition.number;
              }
              vm.resultForm.goodConditionReqList[i].intro = vm.goodCondition.intro;
              vm.resultForm.goodConditionReqList[i].introId = vm.goodCondition.introId;
              addFlag = false;
              break;
            }
            if(i == vm.resultForm.goodConditionReqList.length - 1){
              addFlag = true;
            }
          }
          if(addFlag){
            vm.addGoodConditionReqList();
          }
        }
        else {
           vm.addGoodConditionReqList();
        }

        vm.setAddVisible = false;
      });

    },

    addGoodConditionReqList(){

      if(vm.goodCondition.conditionType == 2){
        vm.resultForm.goodConditionReqList.push({
          goodIds:vm.goodCondition.goodIds,
          conditionType:vm.goodCondition.conditionType,
          number:vm.goodCondition.number * 100,
          numberText:vm.goodCondition.number,
          intro:vm.goodCondition.intro,
          introId:vm.goodCondition.introId
        });
      }
      else {
        vm.resultForm.goodConditionReqList.push({
          goodIds:vm.goodCondition.goodIds,
          conditionType:vm.goodCondition.conditionType,
          number:vm.goodCondition.number,
          numberText:vm.goodCondition.number,
          intro:vm.goodCondition.intro,
          introId:vm.goodCondition.introId
        });
      }

    }

  },
};
</script>

<style lang="less">
.freight-config-content {
  .el-form-item {
    position: relative;
    top: -7px;
    left: 0;
    margin-bottom: 0;
  }
  .el-button {
    position: relative;
    top: -4px;
    left: 0;
  }
}
</style>

<style lang="less" scoped>
.order-detail-wrapper {
  .order-detail-content {
    background: #fff;
    padding: 10px;
    .header-title {
      padding: 10px 12px;
      font-size: 13px;
      color: #449284;
      border-bottom: 1px solid #efefef;
    }
    .freight-config-content {
      margin-top: 60px;
      min-height: 400px;
      .title {
        border-bottom: 0.5px solid #e7e8e9;
        padding-bottom: 6px;
        margin-bottom: 20px;
        color: #373839;
        font-weight: 700;
      }
      .c-row {
        & > span {
          display: inline-block;
          width: 40px;
          margin: 0;
          text-align: center;
          color: #626262;
          &.big {
            width: 70px;
          }
          &.small {
            width: 20px;
            margin: 0 50px 0 0;
          }
          &.middle {
            width: 50px;
          }
        }
      }
    }
  }
}





</style>
