<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    :close-on-click-modal="false"
    width="55%"
    :visible.sync="visible"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      @keyup.enter.native="dataFormSubmit()"
      label-width="80px"
    >
      <el-row v-if="!this.dataForm.id">
        <el-col :span="8">
          <el-form-item label="销售平台">
            <el-select
              v-model="dataForm.blonPlantform"
              clearable
              @change="pfChange"
              placeholder="请选择销售平台"
            >
              <el-option
                v-for="item in pfs"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="店铺">
            <el-select
              v-model="dataForm.store"
              clearable
              @change="storeChange"
              placeholder="请选择店铺"
            >
              <el-option
                v-for="item in stores"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="分组" prop="groupId">
            <el-select v-model="dataForm.groupId" clearable placeholder="请选择分组">
              <el-option
                v-for="item in groups"
                :key="item.id"
                :label="item.groupName"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input v-model="dataForm.name" placeholder="名称"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="早餐个数" prop="breakfastNum">
            <el-input v-model="dataForm.breakfastNum" placeholder></el-input>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="18">
          <el-form-item label="推送渠道" prop="channel">
            <el-radio-group v-model="dataForm.channel">
              <el-radio :label="`H`">飞猪</el-radio>
              <el-radio :label="`O`">商旅</el-radio>
              <el-radio :label="`G`">高德</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="18">
          <el-form-item label="退订政策" prop="cancelPolicy">
            <el-radio-group @change="changePolicy" v-model="dataForm.cancelPolicy">
              <el-radio :label="-1">无</el-radio>
              <el-radio :label="1">任意退</el-radio>
              <el-radio :label="2">不能退</el-radio>
              <el-radio :label="4">条件退</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-button v-if="addPoliceVisible" type="primary" @click="addPolice()"
            >增加</el-button
          >
        </el-col>
      </el-row>



      <el-form-item label-width="0" v-if="addPoliceVisible">
        <el-table :data="dataCancelPolice" border style="width: 100%">
          <el-table-column
            prop="pId"
            header-align="center"
            align="center"
            label="序号"
          ></el-table-column>
          <el-table-column
            prop="preHour"
            header-align="center"
            align="center"
            label="提前X小时前退订"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.preHour"
                placeholder="提前X小时前退订"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            prop="fine"
            header-align="center"
            label="扣除Y%的罚金"
            align="center"
          >
            <template slot-scope="scope">
              <el-input v-model="scope.row.fine" placeholder="扣除Y%的罚金"></el-input>
            </template>
          </el-table-column>
          <el-table-column
            fixed="right"
            header-align="center"
            align="center"
            width="150"
            label="操作"
          >
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="removePolice(scope.row.pId)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-row>
        <el-form-item label="价格区间">
          <el-col :span="6">
            <el-button type="primary" @click="pAddPolice()">增加</el-button>
          </el-col>
        </el-form-item>
      </el-row>

      <el-form-item label-width="0">
        <el-table :data="pDataCancelPolice" border style="width: 100%">
          <el-table-column
            prop="pPId"
            header-align="center"
            align="center"
            width="50"
            label="序号"
          ></el-table-column>
          <el-table-column
            prop="changePriceStart"
            header-align="center"
            align="center"
            label="价格区间始"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.changePriceStart"
                placeholder="开始价格"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column
            prop="changePriceEnd"
            header-align="center"
            label="价格区间止"
            align="center"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.changePriceEnd"
                placeholder="结束价格"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column
            prop="chargePricePercent"
            header-align="center"
            label="加价百分比"
            align="center"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.chargePricePercent"
                placeholder="加价百分比"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column
            prop="chargePriceAmount"
            header-align="center"
            label="加价额"
            align="center"
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.chargePriceAmount"
                placeholder="加价额"
              ></el-input>
            </template>
          </el-table-column>

          <el-table-column
            prop="highestPrice"
            header-align="center"
            label="最高价"
            align="center"
          >
            <template slot-scope="scope">
              <el-input v-model="scope.row.highestPrice" placeholder="最高价"></el-input>
            </template>
          </el-table-column>

          <el-table-column
            fixed="right"
            header-align="center"
            align="center"
            width="50"
            label="操作"
          >
            <template slot-scope="scope">
              <el-button type="text" size="small" @click="pRemovePolice(scope.row.pPId)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
export default {
  data() {
    return {
      visible: false,
      addPoliceVisible: false,
      dataCancelPolice: [],
      pDataCancelPolice: [],
      dataForm: {
        id: 0,
        dtId: null,
        blonPlantform: null,
        store: null,
        groupId: null,
        name: "",
        cancleJsonStr: "",
        cancelPolicy: "",
        breakfastNum: "",
        channel: "H",
        changePricePercent: null,
        changePriceAmount: null,
        highestPrice: null
      },
      pfs: [],
      stores: [],
      groups: [],
      dataRule: {
        name: [{required: true, message: "不能为空", trigger: "blur"}],
        groupId: [{required: true, message: "不能为空", trigger: "blur"}]
      }
    }
  },
  methods: {
    // 查询店铺信息
    getStore() {
      this.$http({
        url: this.$http.adornUrl("/op/group/store"),
        method: "get",
        params: this.$http.adornParams({
          dtId: this.dataForm.dtId,
          pf: this.dataForm.blonPlantform
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.stores = data.list
          this.storeChange(this.dataForm.store)
        }
      })
    },
    // 查询分组信息
    getGroup() {
      this.$http({
        url: this.$http.adornUrl("/op/group/group"),
        method: "get",
        params: this.$http.adornParams({
          dtId: this.dataForm.dtId,
          pf: this.dataForm.blonPlantform,
          storeId: this.dataForm.store
        })
      }).then(({data}) => {
        if (data && data.code === 0) {
          this.groups = data.list
        } else {
          this.groups = []
        }
      })
    },
    // 选择销售平台
    pfChange(value) {
      this.getStore()
    },
    // 选择店铺
    storeChange(value) {
      this.getGroup()
    },
    changePolicy(value) {
      if (value === 4) {
        this.addPoliceVisible = true
        if (this.dataCancelPolice.length <= 0) {
          this.dataCancelPolice.push({pId: this.pId, preHour: 24, fine: 10})
        }
        this.resetCancePoliceId()
      } else {
        this.addPoliceVisible = false
      }
    },
    addPolice() {
      this.dataCancelPolice.push({pId: this.pId, preHour: 24, fine: 10})
      this.resetCancePoliceId()
    },

    pAddPolice() {
      this.pDataCancelPolice.push({
        pPId: this.pPId,
        changePriceStart: 0,
        changePriceEnd: 999999,
        chargePricePercent: 0,
        chargePriceAmount: 0,
        highestPrice: 999999
      })
      this.pResetCancePoliceId()
    },

    pRemovePolice(pPId) {
      if (this.pDataCancelPolice.length <= 1) {
        this.$alert("至少需要有价格政策", "提示", {
          confirmButtonText: "确定",
          callback: (action) => {
          }
        })
        return
      }
      let arr = this.pDataCancelPolice
      arr.splice(
        arr.findIndex((item) => item.pPId === pPId),
        1
      )
      this.pResetCancePoliceId()
    },

    removePolice(pId) {
      if (this.dataCancelPolice.length <= 1) {
        this.$alert("至少需要有一个退订政策", "提示", {
          confirmButtonText: "确定",
          callback: (action) => {
          }
        })
        return
      }
      let arr = this.dataCancelPolice
      arr.splice(
        arr.findIndex((item) => item.pId === pId),
        1
      )
      this.resetCancePoliceId()
    },
    resetCancePoliceId() {
      this.pId = this.dataCancelPolice.length + 1
      let arr = this.dataCancelPolice
      arr.map((value, index, array) => {
        value.pId = index + 1
      })
    },
    pResetCancePoliceId() {
      this.pPId = this.pDataCancelPolice.length + 1
      let arr = this.pDataCancelPolice
      arr.map((value, index, array) => {
        value.pPId = index + 1
      })
    },
    tranCancelPolice(value) {
      if (value === "NONE") {
        return -1
      }
      let policy = null
      this.pId = this.dataCancelPolice.length + 1
      try {
        if (value != null || value !== undefined) {
          let p = JSON.parse(value)
          policy = p.cancelPolicyType
          if (policy === 4) {
            this.addPoliceVisible = true
            let pInfo = p.policyInfo
            Object.keys(pInfo).map((key) => {
              this.dataCancelPolice.push({
                pId: this.pId,
                preHour: key,
                fine: pInfo[key]
              })
              this.pId = this.pId + 1
            })
          } else {
            this.addPoliceVisible = false
          }
        }
      } catch (err) {
        policy = null
        return policy
      }
      return policy
    },
    init(id, dtId, pfs) {
      this.dataForm.id = id || 0
      this.dataForm.dtId = dtId
      this.pfs = pfs
      this.dataForm.blonPlantform = null
      this.dataForm.store = null
      this.dataForm.groupId = null
      this.dataForm.name = null
      this.dataForm.breakfastNum = null
      this.dataForm.cancelPolicy = -1
      this.dataCancelPolice = []
      this.addPoliceVisible = false
      this.visible = true
      this.$nextTick(() => {
        this.$refs["dataForm"].resetFields()
        if (this.dataForm.id) {
          this.$http({
            url: this.$http.adornUrl(`/op/ourrateplan/info/${this.dataForm.id}`),
            method: "get",
            params: this.$http.adornParams()
          }).then(({data}) => {
            if (data && data.code === 0) {
              this.dataForm.name = data.ourRateplan.name
              this.dataForm.store = data.ourRateplan.storeId
              this.dataForm.groupId = data.ourRateplan.groupId
              this.dataForm.cancleJsonStr = data.ourRateplan.cancleJsonStr
              this.dataForm.cancelPolicy = this.tranCancelPolice(
                data.ourRateplan.cancleJsonStr
              )
              this.dataForm.breakfastNum = data.ourRateplan.breakfastNum
              this.dataForm.changePricePercent = data.ourRateplan.changePricePercent
              this.dataForm.changePriceAmount = data.ourRateplan.changePriceAmount
              this.dataForm.highestPrice = data.ourRateplan.highestPrice
              this.pDataCancelPolice = data.ourRateplan.ourRateplanPrices
              this.dataForm.channel = data.ourRateplan.channel
            }
          })
        }
      })
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          let police = this.dataForm.cancelPolicy
          let strPolice = null
          let strPinfo = ""
          switch (police) {
            case -1:
              strPolice = "NONE"
              break
            case 1:
            case 2:
              strPolice = '{"cancelPolicyType":' + police + "}"
              break
            case 4:
              strPolice = '{"cancelPolicyType":4,"policyInfo":{'
              strPinfo = this.dataCancelPolice.reduce((preValue, curValue, index) => {
                return preValue + '"' + curValue.preHour + '":' + curValue.fine + ","
              }, "")
              strPolice = strPolice + strPinfo
              let reg = /,$/gi
              strPolice = strPolice.replace(reg, "}}")
              break
          }
          this.dataForm.cancleJsonStr = strPolice
          this.$http({
            url: this.$http.adornUrl(
              `/op/ourrateplan/${!this.dataForm.id ? "save" : "update"}`
            ),
            method: "post",
            data: this.$http.adornData({
              id: this.dataForm.id || undefined,
              dtId: this.dataForm.dtId,
              storeId: this.dataForm.store,
              groupId: this.dataForm.groupId,
              name: this.dataForm.name,
              cancleJsonStr: this.dataForm.cancleJsonStr,
              breakfastNum: this.dataForm.breakfastNum,
              changePriceAmount: this.dataForm.changePriceAmount,
              changePricePercent: this.dataForm.changePricePercent,
              highestPrice: this.dataForm.highestPrice,
              ourRateplanPrices: this.pDataCancelPolice,
              channel: this.dataForm.channel
            })
          }).then(({ data }) => {
            if (data && data.code === 0) {
              this.$message({
                message: "操作成功",
                type: "success",
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit("refreshDataList")
                  this.pDataCancelPolice = []
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          })
        }
      })
    }
  }
}
</script>
