<template>
  <div class="app-container coupon-add">
    <br>
    <el-row>
      <!-- 模板名称部分 -->
      <el-form ref="addItem" :model="addData" :rules="rules" label-width="120px">
        <el-form-item label="模板名称:" prop="title">
          <el-input v-model="addData.title" :readonly="readonly" placeholder="请输入模板名称" :maxlength="32" show-word-limit
                    style="width: 500px;"/>
        </el-form-item>
        <br>
      </el-form>
      <!-- 买家付费地区 -->
      <el-form label-width="120px">
        <el-form-item label="买家付费区域:">
          <el-form ref="addItemTwo" :model="{shippingTemplateRuleList}" label-width="120px">
            <table style="width: 75%" bordercolor="#ccc" border="1" cellpadding="0" cellspacing="0" class="spec-table">
              <tr>
                <th width="30%">付费区域</th>
                <th width="15%">首件（个）</th>
                <th width="15%">运费（元）</th>
                <th width="15%">续件（个）</th>
                <th width="15%">续费（元）</th>
                <th width="10%">操作</th>
              </tr>
              <tr v-if="shippingTemplateRuleList == ''">
                <td colspan="6">
                  暂无数据
                </td>
              </tr>
              <tr v-for="(item,index) in shippingTemplateRuleList" :key="index" style="">
                <td class="spec-table-td" style="text-align: left">
                  <div style="width: 100%;" v-for="(areas,index) in item.filterList" :key="index" class="spec-table-td-link" >
                    <div>
                      <div style="float: left">{{ areas.city }}</div>
                      <div v-if="areas.provinceList.length > 0">({{ areas.provinceList.join('，') }})</div>
                    </div>
                  </div>
                  <a @click="setListData(item.shippingTemplateRuleAreaList,index+1)" style="color:#00aaff;text-underline: #00aaff;float: right">编辑</a>
                </td>
                <td>
                  <el-form-item :prop="`shippingTemplateRuleList.${index}.defaultNumber`"
                                :rules='[{ required: true, message: "首件不能为空", trigger: "blur" },{ pattern: /^([1-9]\d*)$/, message: "请输入正确的件数", trigger: ["blur", "change"]}]'
                                label-width="0">
                    <el-input v-model="item.defaultNumber" placeholder="请输入内容"></el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item :prop="`shippingTemplateRuleList.${index}.defaultPrice`"
                                :rules="[{ required: true, message: '运费不能为空', trigger: 'blur' },{ pattern: /^([1-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1}))))$/, message: '请输入正确的金额，最多两位小数', trigger: ['blur', 'change'] }]"
                                label-width="0">
                    <el-input v-model="item.defaultPrice" placeholder="请输入内容"></el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item :prop="`shippingTemplateRuleList.${index}.createNumber`"
                                :rules='[{ pattern: /^([0-9]\d*)$/, message: "请输入正确的件数", trigger: ["blur", "change"]}]'
                                label-width="0">
                    <el-input v-model="item.createNumber" placeholder="请输入内容"></el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-form-item :prop="`shippingTemplateRuleList.${index}.createPrice`"
                                :rules="[{ pattern: /^([0-9]\d*(\.\d{1,2})?|([0](\.([0][1-9]|[1-9]\d{0,1}))))$/, message: '请输入正确的金额，最多两位小数', trigger: ['blur', 'change'] }]"
                                label-width="0">
                    <el-input v-model="item.createPrice" placeholder="请输入内容"></el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-button type="text" @click="delRow(item)">删除</el-button>
                </td>
              </tr>
            </table>
            <el-col style="margin-top: 10px">
              <el-button type="primary" size="mini" @click="getListData">添加付费区域</el-button>
            </el-col>

          </el-form>
        </el-form-item>
      </el-form>

      <!-- 不发货地区 -->
      <el-form label-width="120px">
        <el-form-item label="不发货区域:">
          <el-form ref="addItemThree" :model="{shippingTemplateRuleList2}" label-width="120px">
            <table style="width: 75%" bordercolor="#ccc" border="1" cellpadding="0" cellspacing="0" class="spec-table">
              <tr>
                <th width="30%">不发货区域</th>
                <th>原因</th>
                <th width="10%">操作</th>
              </tr>
              <tr v-if="shippingTemplateRuleList2 == ''">
                <td colspan="3">
                  暂无数据
                </td>
              </tr>
              <tr v-for="(item,index) in shippingTemplateRuleList2" :key="index">
                <td class="spec-table-td" style="text-align: left">
                  <div style="width: 100%;" v-for="(areas,index) in item.filterList" :key="index" class="spec-table-td-link" >
                    <div>
                      <div style="float: left">{{ areas.city }}</div>
                      <div v-if="areas.provinceList.length > 0">({{ areas.provinceList.join('，') }})</div>
                    </div>
                  </div>
                  <a @click="setListData(item.shippingTemplateRuleAreaList,shippingTemplateRuleList.length+index+1)" style="color:#00aaff;text-underline: #00aaff;float: right">编辑</a>
                </td>
                <td>
                  <el-form-item :prop="`shippingTemplateRuleList2.${index}.remark`"
                                :rules="{ required: true, message: '原因不能为空', trigger: 'blur' }" label-width="0">
                    <el-input v-model="item.remark" placeholder="请输入内容"></el-input>
                  </el-form-item>
                </td>
                <td>
                  <el-button type="text" @click="delRowTwo(item)">删除</el-button>
                </td>
              </tr>
            </table>
            <el-col style="margin-top: 10px">
              <el-button type="primary" size="mini" @click="getListData2">添加不发货区域</el-button>
            </el-col>
          </el-form>
        </el-form-item>
      </el-form>

      <el-form label-width="120px">
        <el-form-item label="包邮地区:">
          除以上地区外均为包邮地区
        </el-form-item>
      </el-form>
    </el-row>

    <el-row v-if="!readonly">
      <el-col :span="23" style="text-align: right">
        <el-button type="info" @click="$router.go(-1)">取消</el-button>
        <el-button :loading="addIng" type="primary" @click="update()">保存</el-button>
      </el-col>
    </el-row>

    <region-list
      v-if="createShow"
      :dialog-show="createShow"
      :shippingTemplateRuleList="shippingTemplateRuleList" :shippingTemplateRuleList2="shippingTemplateRuleList2"
      :id="id" :list="list"
      @close="close"
    />
  </div>
</template>
<script>
import RegionList from "./components/regionList";
import {
  getTemplateList,
  addTemplateList,
  getTreeList,
  getTemplateDetail,
  setTemplateDetail
} from "@/api/setting/template";
import {accDiv, accMul} from '@/utils/util'
import {addData} from "../../../api/system/dict/data";

export default {
  name: 'TemplateCreate',
  components: {RegionList},
  data() {
    return {
      createShow: false,
      listPidProvince: [],//省
      props: {
        multiple: true,
        value: 'areaId',
        label: 'areaName',
        children: 'cityList',
      },
      id: this.$route.query.id,
      listId:'',
      type:'',
      addIng: false,
      readonly: this.$route.name === 'TemplateQuery',
      shippingTemplateRuleList: [],
      shippingTemplateRuleList2: [],
      addData: {
        title: '',
        shippingTemplateRuleList: [
          {
            createNumber: '',//新增数量
            createPrice: '',//新增价格
            defaultNumber: '',//默认数量
            defaultPrice: '',//默认价格
            type: '',//类型 1发货 2不发货
            shippingTemplateRuleAreaList: [
              {
                city: '',//市
                cityId: '',//市id
                province: '',//省
                provinceId: '',//省id
                remark: '不发货备注',
              }
            ],
          },
        ],
      },
      //运费相关区域列表
      listPid: [],

      rules: {
        title: [{required: true, message: '请输入模板名称', trigger: 'blur'}],
      },
      provinceList:{}//省(市)
    };
  },
  created() {
    this.getList()
    if (this.id) {
      getTemplateDetail(this.id).then(res => {
        const {id, title, shippingTemplateRuleList} = res.data
        shippingTemplateRuleList.map(item => {
          item.createPrice = accDiv(item.createPrice, 100)
          item.defaultPrice = accDiv(item.defaultPrice, 100)
        if (item.type == 1){
          this.shippingTemplateRuleList.push(item)
        }else {
          this.shippingTemplateRuleList2.push(item)
          }
        })
        this.addData = {id, title}
        this.filterList()
      })

    }
  },
  methods: {
    //获取省份
    getList(reset) {
      getTreeList().then(res => {
        if (res.code == 0) {
          this.listPidProvince = res.data || []
        }
      })
    },

    // 关闭弹框
    close(ruleArea) {
      this.createShow = false;
      if(ruleArea == undefined){
        return
      }
      if (this.listId == ''){
        if(this.type == 1){
          let data = {
            createNumber: '',
            createPrice: '',
            defaultNumber: '',
            defaultPrice: '',
            shippingTemplateRuleAreaList: ruleArea,
            type: 1,
          }
          this.shippingTemplateRuleList.push(data);
        }else {
          let data = {
            remark: '',
            shippingTemplateRuleAreaList: ruleArea,
            type: 2,
          }
          this.shippingTemplateRuleList2.push(data)
        }
      }else {
        let shippingTemplateRuleList = [...this.shippingTemplateRuleList,...this.shippingTemplateRuleList2]
        for (let i = 0; i < shippingTemplateRuleList.length; i++) {
          shippingTemplateRuleList[this.listId-1].shippingTemplateRuleAreaList = ruleArea
        }
      }
      this.filterList()
    },

    filterList() {
      let shippingTemplateRuleList = [...this.shippingTemplateRuleList,...this.shippingTemplateRuleList2]
      shippingTemplateRuleList.forEach(item => {
        item.filterList = []
        let data = item.shippingTemplateRuleAreaList
        let cityArr = [... new Set(data.map(item => item.city))]
        for (let i = 0; i < cityArr.length; i++) {
          let obj = {
            city: cityArr[i],
            provinceList: []
          }
          for (let j = 0; j < data.length; j++) {
            if(cityArr[i] == data[j].city) {
              obj.provinceList.push(data[j].province)
            }
          }
          item.filterList.push(obj)
        }
        // //折叠市
        for (let i = 0; i < this.listPidProvince.length; i++) {
          let data = this.listPidProvince[i]
          for (let j = 0; j < item.filterList.length; j++) {
            if(data.areaName == item.filterList[j].city && data.cityList.length == item.filterList[j].provinceList.length){
              item.filterList[j].provinceList = []
            }
          }
        }
      })
    },

    //付费地区
    getListData() {
      this.listId = ""
      this.list = null
      this.type = 1
      this.createShow = true;

    },

    //不包邮地区
    getListData2() {
      this.listId = ""
      this.list = null
      this.type = 2
      this.createShow = true;
    },

    //编辑
    setListData(list,index){
      this.list = list
      this.listId = index
      this.createShow = true;
    },

    update() {
      this.$refs['addItem'].validate((valid) => {
        if (valid) {
        } else {
          return;
        }
      });
      this.$refs['addItemTwo'].validate((valid) => {
        if (valid) {
        } else {
          return;
        }
      });
      this.$refs['addItemThree'].validate((valid) => {
        if (valid) {
        } else {
          return;
        }
      });

      if (this.addData.title == "") {
        this.$message({
          showClose: true,
          message: '模板名称不能为空',
          type: 'warning'
        });
        return;
      }

      //判断付费区域
      if (this.shippingTemplateRuleList) {
        for (let i = 0; i < this.shippingTemplateRuleList.length; i++) {
          let item = this.shippingTemplateRuleList[i]
          if (item.shippingTemplateRuleAreaList == 1 || item.shippingTemplateRuleAreaList.length == 0 || item.defaultNumber == '' || item.defaultPrice == '') {
            this.$message({
              showClose: true,
              message: '请输入完整后再保存',
              type: 'warning'
            });
            return
          }
        }
      }

      //判断不发货区域
      if (this.shippingTemplateRuleList2) {
        for (let i = 0; i < this.shippingTemplateRuleList2.length; i++) {
          let item = this.shippingTemplateRuleList2[i]
          if (item.shippingTemplateRuleAreaList == 1 || item.shippingTemplateRuleAreaList.length == 0 || item.remark == '') {
            this.$message({
              showClose: true,
              message: '请输入完整后再保存',
              type: 'warning'
            });
            return
          }
        }
      }


      let shippingTemplateRuleList = [...this.shippingTemplateRuleList, ...this.shippingTemplateRuleList2]
      for (let i = 0; i < shippingTemplateRuleList.length; i++) {
        if (shippingTemplateRuleList[i].type == 1) {
          shippingTemplateRuleList[i].createPrice = accMul(shippingTemplateRuleList[i].createPrice, 100)
          shippingTemplateRuleList[i].defaultPrice = accMul(shippingTemplateRuleList[i].defaultPrice, 100)
        }
      }
      this.addData.shippingTemplateRuleList = shippingTemplateRuleList

      this.submitForm()
    },

    submitForm() {
      if (this.id) {
        setTemplateDetail(this.addData).then(res => {
          if (res.code === 0) {
            this.$message({
              message: '修改成功!',
              type: 'success'
            })
          }
          this.$store.dispatch('tagsView/delView', this.$route)
          this.$router.go(-1)
        })

      } else {
        addTemplateList(this.addData).then(res => {
          if (res.code === 0) {
            this.$message({
              message: '添加成功!',
              type: 'success'
            })
            this.$store.dispatch('tagsView/delView', this.$route)
            this.$router.go(-1)
          }
        })
      }
    },

    delRow(row) {
      for (let i = 0; i < this.shippingTemplateRuleList.length; i++) {
        if (this.shippingTemplateRuleList[i] == row) {
          this.shippingTemplateRuleList.splice(i, 1)
        }
      }
    },
    delRowTwo(row) {
      for (let i = 0; i < this.shippingTemplateRuleList2.length; i++) {
        if (this.shippingTemplateRuleList2[i] == row) {
          this.shippingTemplateRuleList2.splice(i, 1)
        }
      }
    }

  },
};
</script>
<style lang="scss" scoped>
.spec-table {
  border-collapse: collapse;
  //width: 100%;
  line-height: 32px;
  border-color: #DCDFE6;
  color: #606266;
  font-size: 14px;

  th {
    background-color: #ECECEC;
  }

  td {
    text-align: center;
    padding: 19px 15px;
  }

  .required {
    position: relative;

    span {
      position: relative;
      top: -6px;
      left: 2px;
      font-size: 10px;
      color: red;
    }
  }
  &-td{
    text-align: left;
    &-link{
      display: inline-block;
      font-size: 13px;
      height: 20px;
      line-height: 20px;
      margin: 0;padding: 0;
    }
  }
}
::v-deep .spec-table[data-v-4ba0ac48]{
  line-height: 20px;
}
</style>
