<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>
                  <el-form-item :prop="`shippingTemplateRuleList.${index}.shippingTemplateRuleAreaList`" :rules="[{ required: true, message: '地区不能为空', trigger:['blur','change'] },{ type: 'array', message: '请选择地区' }]" style="width: 100%" label-width="0">
                    <el-cascader @visible-change="listPidDisabled($event,index)" ref="cascaderAdd" :options="listPidProvince" clearable :props="props" v-model="item.shippingTemplateRuleAreaList" style="width: 100%;" ></el-cascader>
                  </el-form-item>
                </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='[{ required: true, message: "件数不能为空", trigger: "blur" },{ pattern: /^([1-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="[{ 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.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>
                  <el-form-item :prop="`shippingTemplateRuleList2.${index}.shippingTemplateRuleAreaList`" :rules="[{ required: true, message: '地区不能为空', trigger:['blur','change'] },{ type: 'array', message: '请选择地区' }]" label-width="0">
                    <el-cascader @visible-change="listPidDisabled($event,shippingTemplateRuleList.length + index)" :options="listPidProvince" clearable :props="props" v-model="item.shippingTemplateRuleAreaList" style="width: 100%;"></el-cascader>
                  </el-form-item>
                </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>

  </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 {
  components: {RegionList},
  data() {
    return {
      listPidProvince:[],//省
      props:{
        multiple: true,
        value:'areaId',
        label:'areaName',
        children:'cityList',
      },
      id: this.$route.query.id,
      select:false,
      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:'不发货备注',
              },{
                city: '',//市
                cityId: '',//市id
                province: '',//省
                provinceId: '',//省id
                remark:'不发货备注',
              },{

              }
            ],
          },
        ],
      },
      //运费相关区域列表
      listPid:[],

      rules: {
        title: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
      }
    };
  },
  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)
          let data = []
          item.shippingTemplateRuleAreaList.map(ressage => {
            data.push([ressage.provinceId,ressage.cityId])
          })
          item.shippingTemplateRuleAreaList = data

          if(item.type == 1){
            this.shippingTemplateRuleList.push(item)
          }
          if(item.type == 2){
            this.shippingTemplateRuleList2.push(item)
          }
        })
        this.addData = {id, title}
      })
    }
  },
  methods: {

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

    //付费地区
    getListData(){
      let data = this.shippingTemplateRuleList[this.shippingTemplateRuleList.length-1] || {}
      if(data.shippingTemplateRuleAreaList == 1 ||data.createNumber == '' || data.createPrice == '' || data.defaultNumber == '' || data.defaultPrice == ''){
        this.$message({
          showClose: true,
          message: '请输入完整后再添加',
          type: 'warning'
        });
        return
      }
      let data2 = {
        createNumber:'',
        createPrice:'',
        defaultNumber:'',
        defaultPrice:'',
        shippingTemplateRuleAreaList:1,
        type:1,
      }
      this.shippingTemplateRuleList.push(data2)
    },

    //不包邮地区
    getListData2(){
      let data = this.shippingTemplateRuleList2[this.shippingTemplateRuleList2.length-1] || {}
      if(data.shippingTemplateRuleAreaList == 1 || data.remark == ''){
        this.$message({
          showClose: true,
          message: '请输入完整后再添加',
          type: 'warning'
        });
        return
      }
      let data2 = {
        remark:'',
        shippingTemplateRuleAreaList:1,
        type:2,
      }
      this.shippingTemplateRuleList2.push(data2)
    },

    listPidDisabled(e,index,){
      let shippingTemplateRuleList = [...this.shippingTemplateRuleList,...this.shippingTemplateRuleList2]
      if(e){
        this.listPidProvince.map(item=>{//省
          item.cityList.map(res=>{//市
            shippingTemplateRuleList.map(listItem=>{//列表
              if(listItem.shippingTemplateRuleAreaList != 1){
                listItem.shippingTemplateRuleAreaList.map(listRes=>{//列表存在的省市
                  if(res.areaId == listRes[1] ){
                    // res.disabled = true
                    this.$set(res,'disabled',true)
                  }
                })
              }
            })
          })
        })
        this.listPidProvince.map(item=>{//省
          item.cityList.map(res=>{//市
            for (let i = 0; i < shippingTemplateRuleList[index].shippingTemplateRuleAreaList.length; i++) {
              if (res.areaId == shippingTemplateRuleList[index].shippingTemplateRuleAreaList[i][1] ){
                this.$delete(res,'disabled',)
              }
            }
          })
        })

      }else {
        this.listPidProvince.map(item=>{
          item.cityList.map(res=>{
            // res.disabled = false
            this.$set(res,'disabled',false)
          })
        })
      }
    },

    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;
      }

      let arr = []
      //判断付费区域
      if (this.shippingTemplateRuleList){
        for (let i = 0; i < this.shippingTemplateRuleList.length; i++) {
          let item = this.shippingTemplateRuleList[i]
          if(item.shippingTemplateRuleAreaList == 1 || item.createNumber == '' || item.createPrice == '' || item.defaultNumber == '' || item.defaultPrice == ''){
            this.$message({
              showClose: true,
              message: '请输入完整后再保存',
              type: 'warning'
            });
            return
          }
        }
        this.shippingTemplateRuleList.map(item =>{
          let ressage = []
          item.shippingTemplateRuleAreaList.map(res=>{
            let city = ''
            let province = ''
            for (let i = 0; i < this.listPidProvince.length; i++) {
              if(this.listPidProvince[i].areaId == res[0]){
                city =  this.listPidProvince[i].areaName
                let cityList =  this.listPidProvince[i].cityList
                for (let j = 0; j < cityList.length ; j++) {
                  if(cityList[j].areaId == res[1]){
                    province = cityList[j].areaName
                  }
                }
              }
            }
            res = {
              provinceId:res[0],
              cityId:res[1],
              city:city,
              province:province,
            }
            ressage.push(res)
          })
          item.shippingTemplateRuleAreaList = ressage
          arr.push(item)
        })
      }
      //判断不发货区域
      if(this.shippingTemplateRuleList2){
        for (let i = 0; i < this.shippingTemplateRuleList2.length; i++) {
          let item = this.shippingTemplateRuleList2[i]
          if(item.shippingTemplateRuleAreaList == 1 || item.remark == ''){
            this.$message({
              showClose: true,
              message: '请输入完整后再保存',
              type: 'warning'
            });
            return
          }
        }
        this.shippingTemplateRuleList2.map(item =>{
          let ressage = []
            item.shippingTemplateRuleAreaList.map(res=>{
              let city = ''
              let province = ''
              for (let i = 0; i < this.listPidProvince.length; i++) {
                if(this.listPidProvince[i].areaId == res[0]){
                  city =  this.listPidProvince[i].areaName
                  let cityList =  this.listPidProvince[i].cityList
                  for (let j = 0; j < cityList.length ; j++) {
                    if(cityList[j].areaId == res[1]){
                      province = cityList[j].areaName
                    }
                  }
                }
              }
              res = {
                provinceId:res[0],
                cityId:res[1],
                city:city,
                province:province,
              }
              ressage = res
            })
            item.shippingTemplateRuleAreaList = ressage
            arr.push(item)
        })
      }
      if(arr == ""){
        this.$message({
          showClose: true,
          message: '请至少添加一个区域',
          type: 'warning'
        });
        return;
      }else {
        for (let i = 0; i < arr.length; i++) {
          if(arr[i].type == 1){
            arr[i].createPrice = accMul(arr[i].createPrice,100)
            arr[i].defaultPrice = accMul(arr[i].defaultPrice,100)
          }
        }
        this.addData.shippingTemplateRuleList = arr
        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: 15px;
  }
  .required {
    position: relative;
    span {
      position: relative;
      top: -6px;
      left: 2px;
      font-size: 10px;
      color: red;
    }
  }

}
</style>
