<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"
                style="width: 410px"
                placeholder="请输入"
                maxLength="10"
              ></el-input>
            </el-form-item>
          </el-row>
          <el-row style="margin: 50px 0 0 220px;">
            <el-button
              :disabled="btnDisabled"
              type="primary"
              size="small"
              @click="beforSave()"
            >保存</el-button
            >
          </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="tableData" border class="item-table" style="width: 100%;margin-top: 30px;">
        <el-table-column prop="goodsIdList" label="商品ID" min-width="100" align="center">
          <template slot-scope="scope">
            <div v-for="(item, index) in scope.row.goodsIdList" :key="index">
            <div style="cursor: pointer;color: #449284" @click="viewGoods(item)">{{item.goodsId}}</div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="condition" label="包邮条件" min-width="100" align="center"></el-table-column>
        <el-table-column prop="desc" 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)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <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="setPriceForm"
                 :rules="addRules"
                 :model="model"
                 label-width="250px"
                 label-suffix=":"
                 label-position="right"
                 size="mini"
                 style="width: 100%;">

          <el-form-item label="适用商品ID" class="required-label" prop="userName">
            <el-col :span="12">
              <el-select v-model="model.userName"
                         filterable
                         remote
                         placeholder="请输入专家姓名或医院名称,多个关键字用空格隔开，至少输入两个字符"
                         clearable
                         style="width: 130%;"
                         :remote-method="remoteMethod"
                         :disabled="isEdit"
                         @change="nameChange"
                         @visible-change="noSelectHand">
                <el-option
                  v-for="item in nameList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                  <span>{{item.value}}</span>
                </el-option>
              </el-select>
            </el-col>
          </el-form-item>

          <el-form-item label="包邮条件" class="required-label">
            <el-col :span="4">
              <el-select
                v-model="model.type"
                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="model.type == 1" v-model="model.title" style="margin-left: 5px;" size="small" :precision="0" :min="1" :max="100000"></el-input-number>
              <el-input-number v-if="model.type == 2" v-model="model.title" style="margin-left: 5px;" size="small" :precision="2" :min="0.00" :max="99999.99"></el-input-number>
              <span style="margin-left: 5px;" v-if="model.type == 1">件包邮</span>
              <span style="margin-left: 5px;" v-if="model.type == 2">元包邮</span>
            </el-col>
          </el-form-item>
          <el-form-item label="运费说明" class="required-label">
            <el-col :span="15">
              <el-input v-model="model.title" 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="submit">保存</el-button>
            </span>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import BreadCrumb from "@/components/breadcrumb.vue";
import { getExpressFee, createOrModifyExpressFee } from "@/utils/freight";

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: "",
        list: [
          {
            fee: 0,
            rangeMin: 0,
            rangeMax: 0,
          },
        ],
      },
      model:{
        type:1,
        userName: "",
      },
      typeList: [
        {
          label: '件数',
          value: 1,
        }, {
          label: '金额',
          value: 2,
        }],
      title:"添加条件",
      setAddVisible: false,
      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() {
    this.getExpressFeeInfo();
    this.tableData = [{goodsIdList: [{goodsId:119895},{goodsId:119894}], condition:"满3件包邮",desc:"单品满3件包邮"}];
  },
  methods: {

    // 对数据进行处理
    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,
      });
    },

    // 删除条件
    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.save();
          })
          .catch(() => {});
      });
    },

    // 保存
    save() {
      this.btnDisabled = true;
      let formData = JSON.parse(JSON.stringify(this.formData));
      formData.list = this.dataHandler(formData.list, false);
      createOrModifyExpressFee(formData)
        .then((res) => {
          if (res.code == "000000") {
            this.getExpressFeeInfo();
            this.$message({ type: "success", message: "保存成功!" });
          } else {
            this.$message({ type: "error", message: "保存失败!" });
          }
        })
        .finally((res) => {
          this.btnDisabled = false;
        });
    },
    // 查看商品详情
    viewGoods(row){
      // url = `/create-good?id=${row.goodsId}&storeId=${this.searchForm.storeId}&goodsType=${goodsType}&commissionFlag=${this.commissionFlag}`
      let url = `/create-good?id=${row.goodsId}&storeId=5344&goodsType=5&commissionFlag=1`
    // this.$store.dispatch('goodsManage/changeGoodsInfo', {...row});
    this.$router.push({
      path: url
    })
    },
    addGoodsCondition(){
      this.title = "添加条件";
      this.setAddVisible = true;

    },
    editGoodsFreight(){
      this.title = "修改条件";
      this.setAddVisible = true;
    },
    delGoodsFreight(){
      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(() => {});
    }
  },
};
</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: 500px;
      .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>
