<template>
  <div class="add-freight-page">
    <Card v-if="loading" class="loading-card">
      <Spin fix size="large" />
    </Card>
    <Card v-else>
      <div class="item">
        <label class="label">模板名称：</label>
        <Input
          placeholder="请输入模板名称"
          v-model="form.templateName"
          :maxlength="20"
          clearable
          style="width: 400px"
        />
      </div>
      <div class="item">
        <label class="label">发货地址：</label>
        <Select
          placeholder="请选择发货地址"
          v-model="form.deliveryAddressId"
          style="width: 400px"
        >
          <Option
            v-for="(item, index) of addressList"
            :value="item.addressId"
            :key="'series-option-' + index"

          >{{ item.addressName }}</Option
          >
        </Select>
      </div>
      <div class="item">
        <label class="label">运费设置：</label>
        <RadioGroup v-model="form.billingType">
          <Radio :label="1" class="ivu-radio">阶梯计价</Radio>
          <Radio :label="2" class="ivu-radio">固定收费</Radio>
        </RadioGroup>
      </div>
      <div class="item" v-if="form.billingType == 2">
        <label class="label">运费金额：</label>
        <Input
          v-model="form.freightAmount"
          clearable
          style="width: 120px"
          type="number"
        >
        <span slot="append">元</span>
        </Input>
      </div>
      <div class="item" v-if="form.billingType == 1">
        <label class="label">计价方式：</label>
        <RadioGroup v-model="form.pricingType">
          <Radio :label="1" class="ivu-radio">按件数</Radio>
          <Radio :label="2" class="ivu-radio">按重量</Radio>
        </RadioGroup>
      </div>
      <div class="item" v-if="form.billingType == 1">
        <label class="label">默认运费：</label>
        <div class="list" v-if="form.pricingType == 1">
          <Input
            v-model="form.baseNumber"
            clearable
            style="width: 80px"
            type="number"
          />
          <span slot="append" style="margin-left: 10px">件以内，</span>
          <Input
            v-model="form.baseAmount"
            clearable
            style="width: 80px"
            type="number"
          />
          <span slot="append" style="margin-left: 10px">元，每增加 </span>
          <Input
            v-model="form.addNumber"
            clearable
            style="width: 80px"
            type="number"
          />
          <span slot="append" style="margin-left: 10px">件，增加运费 </span>
          <Input
            v-model="form.addCost"
            clearable
            style="width: 80px"
            type="number"
          />
          <span slot="append" style="margin-left: 10px">元</span>
        </div>
        <div class="list" v-if="form.pricingType == 2">
          <Input
            v-model="form.baseNumber"
            clearable
            style="width: 80px"
            type="number"
          />
          <span slot="append" style="margin-left: 10px">kg以内，</span>
          <Input
            v-model="form.baseAmount"
            clearable
            style="width: 80px"
            type="number"
          />
          <span slot="append" style="margin-left: 10px">元，每增加 </span>
          <Input
            v-model="form.addNumber"
            clearable
            style="width: 80px"
            type="number"
          />
          <span slot="append" style="margin-left: 10px">kg，增加运费 </span>
          <Input
            v-model="form.addCost"
            clearable
            style="width: 80px"
            type="number"
          />
          <span slot="append" style="margin-left: 10px">元</span>
        </div>
      </div>
<!--      <div class="item">-->
<!--        <label class="label">是否默认：</label>-->
<!--        <i-switch @on-change="handleChange">-->
<!--          <span slot="open">是</span>-->
<!--          <span slot="close">否</span>-->
<!--        </i-switch>-->
<!--      </div>-->
      <Tabs value="name1" v-if="form.billingType == 1">
        <TabPane label="指定地区运费" name="name1">
          <div class="tips">
            除指定地区外，其余地区运费采用：“默认运费”
          </div>
          <Button type="primary" style="margin: 10px" @click="handleAddArea(1)">添加地区</Button>
          <Table :columns="columns" :data="tableData1">
            <template slot-scope="{ row }" slot="deliveryArea">
              <Tag v-for="(item, index) of row.deliveryArea" :key="'area-tag-'+index">{{areaObj[item].name}}</Tag>
            </template>
            <template slot-scope="{ row, index }" slot="pricingType">
              <div class="list" v-if="form.pricingType == 1">
                <Input
                  v-model="row.baseNumber"
                  clearable
                  style="width: 80px"
                  type="number"
                  @input="handleInput(row,index)"
                />
                <span slot="append" style="margin-left: 10px">件以内，</span>
                <Input
                  v-model="row.baseAmount"
                  clearable
                  style="width: 80px"
                  type="number"
                  @input="handleInput(row,index)"
                />
                <span slot="append" style="margin-left: 10px">元，每增加 </span>
                <Input
                  v-model="row.addNumber"
                  clearable
                  style="width: 80px"
                  type="number"
                  @input="handleInput(row,index)"
                />
                <span slot="append" style="margin-left: 10px">件，增加运费 </span>
                <Input
                  v-model="row.addCost"
                  clearable
                  style="width: 80px"
                  type="number"
                  @input="handleInput(row,index)"
                />
                <span slot="append" style="margin-left: 10px">元</span>
              </div>
              <div class="list" v-if="form.pricingType == 2">
                <Input
                  v-model="row.baseNumber"
                  clearable
                  style="width: 80px"
                  type="number"
                  @input="handleInput(row,index)"
                />
                <span slot="append" style="margin-left: 10px">kg以内，</span>
                <Input
                  v-model="row.baseAmount"
                  clearable
                  style="width: 80px"
                  type="number"
                  @input="handleInput(row,index)"
                />
                <span slot="append" style="margin-left: 10px">元，每增加 </span>
                <Input
                  v-model="row.addNumber"
                  clearable
                  style="width: 80px"
                  type="number"
                  @input="handleInput(row,index)"
                />
                <span slot="append" style="margin-left: 10px">kg，增加运费 </span>
                <Input
                  v-model="row.addCost"
                  clearable
                  style="width: 80px"
                  type="number"
                  @input="handleInput(row,index)"
                />
                <span slot="append" style="margin-left: 10px">元</span>
              </div>
            </template>
            <template slot-scope="{ row, index }" slot="remark">
              <Input
                v-model="row.remark"
                clearable
                type="textarea"
              />
            </template>
            <template slot-scope="{ row, index }" slot="operate">
              <Button type="error" size="small" @click="handleDeletePrice(row,index)">删除</Button>
              <Button
                type="primary"
                size="small"
                style="margin-left: 5px"
                @click="handleUpdatePrice(row,index)"
              >修改地区</Button>
            </template>
          </Table>
        </TabPane>
        <TabPane label="指定条件包邮" name="name2">
          <Button type="primary" style="margin-bottom: 10px"  @click="handleAddArea(2)">添加地区</Button>
          <Table :columns="columns" :data="tableData2">
            <template slot-scope="{ row }" slot="deliveryArea" >
              <Tag v-for="(item, index) of row.deliveryArea" :key="'area-tag-'+index">{{areaObj[item].name}}</Tag>
            </template>
            <template slot-scope="{ row, index }" slot="pricingType">
              <div class="list">
                <span slot="append" style="margin-right: 10px">满</span>
                <Input
                  v-model="row.freeShippingAmount"
                  clearable
                  style="width: 80px"
                  type="number"
                  @input="handleInput(row,index)"
                />
                <Select placeholder="" @on-change="handleChange(row)" v-bind:transfer="true" v-model="row.pricingType" style="width:50px">
                  <Option :value="3" key="3">元</Option>
                  <Option :value="4" key="4">件</Option>
                </Select>
                <span slot="append" style="margin-left: 10px">包邮</span>
              </div>
            </template>
            <template slot-scope="{ row, index }" slot="remark">
              <Input
                v-model="row.remark"
                @input="handleInput(row,index)"
                type="textarea"
              />
            </template>
            <template slot-scope="{ row, index }" slot="operate">
              <Button type="error" size="small" @click="handleDeletePrice(row,index)">删除</Button>
              <Button
                type="primary"
                size="small"
                style="margin-left: 5px"
                @click="handleUpdatePrice(row,index)"
              >修改地区</Button>
            </template>
          </Table>
        </TabPane>
        <TabPane label="不能下单地区" name="name3">
          <Button type="primary" style="margin-bottom: 10px" @click="handleAddArea(3)">添加地区</Button>
          <Table :columns="columns" :data="tableData3">
            <template slot-scope="{ row }" slot="deliveryArea">
              <Tag v-for="(item, index) of row.deliveryArea" :key="'area-tag-'+index">{{areaObj[item].name}}</Tag>
            </template>
            <template slot-scope="{ row, index }" slot="pricingType">
              <div class="list">
                不能下单地区
              </div>
            </template>
            <template slot-scope="{ row, index }" slot="remark">
              <Input
                v-model="row.remark"
                @input="handleInput(row,index)"
                type="textarea"
              />
            </template>
            <template slot-scope="{ row, index }" slot="operate">
              <Button type="error" size="small" @click="handleDeletePrice(row,index)">删除</Button>
              <Button
                type="primary"
                size="small"
                style="margin-left: 5px"
                @click="handleUpdatePrice(row,index)"
              >修改地区</Button>
            </template>
          </Table>
        </TabPane>
      </Tabs>
      <div class="footer-con">
        <Button
          type="primary"
          @click="handleSubmit"
          :loading="submitLoading"
          style="margin-left:45%;"
        >保 存</Button
        >
      </div>
    </Card>
    <Modal v-model="isShow"
           title="选择地区"
           :mask-closable="false"
           :closable="false"
    >
      <div class="item-list">
        <CheckboxGroup v-model="templateList.deliveryArea">
          <Checkbox
            class="check-icon"
            :label="key"
            v-for="(item, key) of areaObj"
            :key="'area-check-' + key"
            :disabled="judgeAreaDisable(item, templateList.index)"
          >{{item.name}}</Checkbox>
        </CheckboxGroup>
      </div>
      <div slot="footer">
        <Button
          @click="handleCancelArea"
        >取消</Button
        >
        <Button
          type="primary"
          @click="handleSubmitArea"
        >确定</Button
        >
      </div>
    </Modal>
  </div>
</template>

<script>
import { mapMutations } from 'vuex'
export default {
  name: 'add-freight',
  computed: {
    tableData1 () {
      return this.form.templateItemList.filter((item) => {
        return item.templateType == 1 || item.pricingType == 1 || item.pricingType == 2
      })
    },
    tableData2 () {
      return this.form.templateItemList.filter((item) => {
        return item.templateType == 2 || item.pricingType == 3 || item.pricingType == 4
      })
    },
    tableData3 () {
      return this.form.templateItemList.filter((item) => {
        return item.templateType == 3 || item.pricingType == 5
      })
    },
    isEdit () {
      return Boolean(this.form.templateId)
    }
  },
  data () {
    return {
      loading: false,
      indeterminate: true,
      checkAll: false,
      checkAllGroup: [],
      form: {
        updateTime: '',
        addCost: '',
        addNumber: '',
        baseAmount: '',
        baseNumber: '',
        billingType: '',
        templateId: '',
        deliveryAddressId: '',
        freightAmount: '',
        merchantId: '',
        pricingType: '',
        // isDefault: false,
        templateItemList: [
        ],
        templateName: ''
      },
      isShow: false,
      columns: [
        {
          title: '运送地区',
          slot: 'deliveryArea',
          width: 160,
          align: 'center'
        },
        {
          title: '计费规则',
          slot: 'pricingType',
          minWidth: 200,
          align: 'center'
        },
        {
          title: '备注',
          slot: 'remark',
          width: 150,
          align: 'center'
        },
        {
          title: '操作',
          slot: 'operate',
          width: 200,
          align: 'center'
        }
      ],
      templateList: {
        index: '',
        addCost: 0,
        addNumber: 0,
        baseAmount: 0,
        baseNumber: 0,
        deliveryArea: [],
        freeShippingAmount: 0,
        pricingType: 0,
        remark: '',
        initialArea: []
      },
      areaObj: [],
      submitLoading: false,
      addressList: [],
      routeName: ''
    }
  },
  methods: {
    requestData () {
      this.loading = true
      this.api({
        apiName: 'getTemplateList',
        complete: () => {
          setTimeout(() => {
            this.loading = false
          }, 500)
        },
        success: (res) => {
          if (res.data.length) {
            this.getTemplateDetail(res.data[0].templateId)
          }
        }
      })
    },
    getTemplateDetail (templateId) {
      this.api({
        apiName: 'detailTemplate',
        postdata: templateId,
        complete: () => {
          this.loading = false
        },
        success: (res) => {
          let { templateName, deliveryAddressId, billingType, freightAmount, pricingType, baseNumber, baseAmount, addNumber, addCost, templateItemList, updateTime, templateId } = res.data
          this.form.templateName = templateName
          this.form.deliveryAddressId = deliveryAddressId
          this.form.billingType = billingType
          this.form.freightAmount = freightAmount
          this.form.pricingType = pricingType
          this.form.baseNumber = baseNumber
          this.form.baseAmount = baseAmount
          this.form.addNumber = addNumber
          this.form.addCost = addCost
          this.form.templateId = templateId
          if (templateItemList.length) {
            this.form.templateItemList = templateItemList.map((item) => {
              let { deliveryArea, ...other } = item
              return {
                deliveryArea: deliveryArea.split(','),
                ...other
              }
            })
          }
          for (let i = 0; i < templateItemList.length; i++) {
            let area = templateItemList[i].deliveryArea.split(',')
            for (let j = 0; j < area.length; j++) {
              area[j] += ''
              this.areaObj[area[j]].priceIndex = i
            }
          }
          // let area = ''
          // templateItemList.forEach((item, index) => {
          //   if (index == templateItemList.length - 1) {
          //     area += item.deliveryArea
          //   } else {
          //     area += item.deliveryArea + ','
          //   }
          // })
          // this.templateList.deliveryArea = area.split(',')
          this.form.updateTime = updateTime
        }
      })
    },
    handleInput (val, index) {
      this.form.templateItemList.forEach((item, index) => {
        if (JSON.stringify(item.deliveryArea) == JSON.stringify(val.deliveryArea)) {
          this.form.templateItemList[index] = val
        }
      })
    },
    handleChange (val) {
      this.form.templateItemList.forEach((item, index) => {
        if (JSON.stringify(item.deliveryArea) == JSON.stringify(val.deliveryArea)) {
          this.form.templateItemList[index] = val
        }
      })
    },
    checkForm () {
      let {
        templateName,
        deliveryAddressId,
        billingType,
        freightAmount,
        pricingType,
        baseNumber,
        baseAmount,
        addNumber,
        addCost
      } = this.form
      let errMsg = ''
      if (!billingType) {
        errMsg = '请选择运费设置！'
      }
      if (!deliveryAddressId) {
        errMsg = '请选择发货地址！'
      }
      if (!templateName) {
        errMsg = '请输入模板名称！'
      }
      if (billingType == 2) {
        freightAmount = parseFloat(freightAmount)
        if (!/^[0-9]+(.[0-9]{1,2})?$/.test(freightAmount)) {
          errMsg = '运费金额 最多至小数点后两位！'
        }
        if ((freightAmount <= 0 || freightAmount > 999999)) {
          errMsg = '运费金额 格式不正确！'
        }
        if (!freightAmount) {
          errMsg = '请输入运费金额！'
        }
      }
      if (billingType == 1) {
        addCost = parseFloat(addCost)
        if (!/^[0-9]+(.[0-9]{1,2})?$/.test(addCost)) {
          errMsg = '默认运费 增加运费 最多至小数点后两位！'
        } if ((addCost <= 0 || addCost > 999999)) {
          errMsg = '默认运费 增加运费 格式不正确！'
        }
        baseAmount = parseFloat(baseAmount)
        if (!/^[0-9]+(.[0-9]{1,2})?$/.test(baseAmount)) {
          errMsg = '默认运费 运费金额 最多至小数点后两位！'
        }
        if ((baseAmount <= 0 || baseAmount > 999999)) {
          errMsg = '默认运费 运费金额 格式不正确！'
        }
        if (addNumber < 0 || !/^\d+$/.test(addNumber) || addNumber > 99999999) {
          errMsg = '默认运费中有字段输入有误！'
        }
        if (baseNumber < 0 || !/^\d+$/.test(baseNumber) || baseNumber > 99999999) {
          errMsg = '默认运费中有字段输入有误！'
        }
        if (!baseNumber || !baseAmount || !addNumber || !addCost) {
          errMsg = '请输入默认运费！'
        }
        if (!pricingType) {
          errMsg = '请选择计价方式！'
        }
        this.form.templateItemList.forEach((item) => {
          if (item.pricingType == 1 || item.pricingType == 2) {
            // item.pricingType = pricingType
            item.addCost = parseFloat(item.addCost)
            if (!/^[0-9]+(.[0-9]{1,2})?$/.test(item.addCost)) {
              errMsg = '指定地区运费 增加运费 最多至小数点后两位！'
            }
            if (item.addCost <= 0 || item.addCost > 999999) {
              errMsg = '指定地区运费 增加运费 格式不正确！'
            }
            item.baseAmount = parseFloat(item.baseAmount)
            if (!/^[0-9]+(.[0-9]{1,2})?$/.test(item.baseAmount)) {
              errMsg = '指定地区运费 运费金额 最多至小数点后两位！'
            }
            if (item.baseAmount <= 0 || item.baseAmount > 999999) {
              errMsg = '指定地区运费 运费金额 格式不正确！'
            }
            if (item.addNumber < 0 || !/^\d+$/.test(item.addNumber) || item.addNumber > 99999999) {
              errMsg = '指定地区运费中有字段输入有误！'
            }
            if (item.baseNumber < 0 || !/^\d+$/.test(item.baseNumber) || item.baseNumber > 99999999) {
              errMsg = '指定地区运费中有字段输入有误！'
            }
            if (!item.baseNumber || !item.baseAmount || !item.addNumber || !item.addCost) {
              errMsg = '请输入指定地区运费！'
            }
          }
          if (item.pricingType == 3 || item.pricingType == 4) {
            if (!item.freeShippingAmount) {
              errMsg = '请输入指定条件包邮 满足条件 ！'
            }
          }
        })
      }

      return { errMsg }
    },
    handleSubmit () {
      let { errMsg } = this.checkForm()
      if (errMsg) {
        this.$Message.warning({
          content: errMsg,
          duration: 3
        })
        return
      }
      this.form.templateItemList = this.form.templateItemList.map((item) => {
        let { deliveryArea, pricingType, ...other } = item
        return {
          deliveryArea: deliveryArea.join(','),
          pricingType: (pricingType == 1 || pricingType == 2) ? this.form.pricingType : pricingType,
          ...other
        }
      })
      // console.log(this.form)
      // return;
      let apiName = this.form.templateId ? 'updateTemplate' : 'addTemplate'
      let title = this.form.templateId ? '编辑成功！' : '保存成功！'
      this.api({
        apiName: apiName,
        postdata: this.form,
        complete: () => {
          this.submitLoading = false
        },
        success: (res) => {
          this.$Notice.success({ title })
          this.requestData()
        }
      })
    },
    judgeAreaDisable (item, index) {
      return item.priceIndex != null && item.priceIndex != index
    },
    clearAreaForm () {
      this.templateList = {
        index: null,
        addCost: 0,
        addNumber: 0,
        baseAmount: 0,
        baseNumber: 0,
        deliveryArea: [],
        freeShippingAmount: 0,
        pricingType: 0,
        remark: '',
        initialArea: [],
        templateType: ''
      }
    },
    handleAddArea (type) {
      if (!this.form.pricingType) {
        this.$Message.warning('请先选择计价方式')
        return
      }
      this.templateType = type
      this.templateList.index = null
      this.isShow = true
    },
    // handleCheckAll () {
    //   if (this.indeterminate) {
    //     this.checkAll = false
    //   } else {
    //     this.checkAll = !this.checkAll
    //   }
    //   this.indeterminate = false
    //
    //   if (this.checkAll) {
    //     this.checkAllGroup = this.areaData
    //   } else {
    //     this.checkAllGroup = []
    //   }
    // },
    // checkAllGroupChange (data) {
    //   this.checkAllGroup = data
    //   if (data.length === 3) {
    //     this.indeterminate = false
    //     this.checkAll = true
    //   } else if (data.length > 0) {
    //     this.indeterminate = true
    //     this.checkAll = false
    //   } else {
    //     this.indeterminate = false
    //     this.checkAll = false
    //   }
    // },
    handleUpdatePrice (row, index) {
      this.templateList = JSON.parse(JSON.stringify(row))
      this.form.templateItemList.forEach((item, ind) => {
        if (JSON.stringify(item.deliveryArea) == JSON.stringify(row.deliveryArea)) {
          this.templateList.index = ind
        }
        this.templateList.initialArea = this.templateList.deliveryArea.slice(0)
      })

      this.isShow = true
    },
    handleDeletePrice (row, index) {
      this.form.templateItemList.forEach((item, index) => {
        if (JSON.stringify(item.deliveryArea) == JSON.stringify(row.deliveryArea)) {
          item.deliveryArea.forEach((val) => {
            this.areaObj[val].priceIndex = null
          })
          this.form.templateItemList.splice(index, 1)
        }
      })
    },
    handleCancelArea () {
      this.isShow = false
      this.clearAreaForm()
    },
    handleSubmitArea () {
      let {
        index,
        deliveryArea,
        initialArea
      } = this.templateList
      let { templateType } = this
      if (!deliveryArea.length) {
        this.$Message.warning('请选择地区！')
        return
      }
      if (!index && index != 0) {
        // 添加
        this.form.templateItemList.push({
          addCost: '',
          addNumber: '',
          baseAmount: '',
          baseNumber: '',
          deliveryArea,
          freeShippingAmount: '',
          pricingType: templateType == 1 ? this.form.pricingType : (templateType == 3) ? 5 : 3,
          remark: '',
          templateType
        })
        index = this.form.templateItemList.length - 1
      } else {
        // 更新
        this.$set(this.form.templateItemList, index, {
          addCost: '',
          addNumber: '',
          baseAmount: '',
          baseNumber: '',
          deliveryArea,
          freeShippingAmount: '',
          pricingType: templateType == 1 ? this.form.pricingType : (templateType == 3) ? 5 : 3,
          remark: '',
          templateType
        })
      }

      initialArea.forEach((item) => {
        this.areaObj[item].priceIndex = null
      })
      deliveryArea.forEach((item) => {
        this.areaObj[item].priceIndex = index
      })
      this.clearAreaForm()
      this.isShow = false
    },
    requestAreaList () {
      this.api({
        apiName: 'getDictCnProvinceList',
        success: (res) => {
          let areaObj = {}
          res.data.forEach((item) => {
            item.provinceList.forEach(val => {
              areaObj[val.code] = { name: val.areaName, priceIndex: null }
            })
          })
          this.areaObj = areaObj
        }
      })
    },
    reuestAddress () {
      this.api({
        apiName: 'getAddressList',
        success: (res) => {
          this.addressList = res.data
        }
      })
    }
  },
  mounted () {
    this.requestAreaList()
    this.reuestAddress()
    setTimeout(() => {
      this.requestData()
    })
  }
}
</script>

<style scoped lang="less">
  .add-freight-page {

    .loading-card {
      height: 100%;
    }
    .head {
      color: #17233d;
      font-size: 18px;
      font-weight: bold;
      display: flex;
      align-items: center;
      margin-bottom: 15px;
      i {
        margin-right: 10px;
      }
    }
    .item {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      .ivu-radio{
        width: 200px;
      }
    }
    .item .label {
      display: block;
      width: 150px;
      text-align: right;
    }
    .footer-con {
      display: flex;
      text-align: center;
      margin-top: 10px;
    }
  }
  /deep/.ivu-checkbox-wrapper {
    margin: 8px;
  }
</style>
