<template>
  <div class="container">
    <ComHeader :title="title">
      <div slot="options">
        <el-button type="primary" size="mini" @click="submit">保 存</el-button>
      </div>
    </ComHeader>
    <div class="form">
      <el-form ref="form" :model="form" :rules="rules" class="custom-form-label" label-width="120px" label-position="left">
        <div class="com-line-title">基础设置</div>
        <el-row :gutter="0">
          <el-col :span="12">
            <el-form-item label="收费标准名称：" prop="charge_name">
              <el-input v-model="form.charge_name" placeholder="收费标准名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="门店归属：" prop="shop_id">
              <lazy-tree
                ref="addTree"
                :tree="form.shop_name"
                :disabled="!!$route.query.sn"
                input-width="400px"
                is-gap
                style="margin-bottom: 0;display:flex;width:100%"
                @handleSelectGroup="selectGroup"
              />
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="服务费规则：" prop="service_fee_type">
              <el-checkbox-group v-model="form.service_fee_type">
                <el-checkbox label="1">按时间</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计费类型：" prop="charge_way">
              <el-radio-group v-model="form.charge_way">
                <el-radio label="2">按电量</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="满电功率：" prop="full_power">
              <el-input v-model="form.full_power" type="number" placeholder="满电功率">
                <template slot="append">W</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="过载功率：" prop="over_power">
              <el-input v-model="form.over_power" type="number" placeholder="过载功率">
                <template slot="append">W</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="判满延时：" prop="full_delay">
              <el-input v-model="form.full_delay" type="number" placeholder="判满延时">
                <template slot="append">秒</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="拔掉停充延时：" prop="off_delay">
              <el-input v-model="form.off_delay" type="number" placeholder="拔掉停充延时">
                <template slot="append">秒</template>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="退款渠道：" prop="refund_type">
              <el-radio-group v-model="form.refund_type">
                <el-radio :label="1">退钱包</el-radio>
                <el-radio :label="2">原路返回</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>

        </el-row>

        <div class="title-row">
          <div class="com-line-title mb0">服务费配置</div>
          <el-tooltip content="新增服务费配置" placement="top">
            <i class="el-icon-circle-plus-outline icon" @click="addItem('service_fee')" />
          </el-tooltip>
        </div>
        <el-table :data="form.service_fee">
          <el-table-column align="center" label="序号" width="120">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="功率">
            <template slot-scope="scope">
              <div style="display: flex;justify-content: center;">
                <el-input
                  v-model="scope.row.begin_power"
                  size="mini"
                  maxlength="6"
                  style="width: 240px;"
                  placeholder="开始功率"
                  @input="limitDecimalPlaces(scope.row, 'begin_power')"
                >
                  <template slot="append">W</template>
                </el-input>
                <div style="margin: 0 10px;">-</div>
                <el-input
                  v-model="scope.row.end_power"
                  size="mini"
                  maxlength="6"
                  style="width: 240px;"
                  placeholder="结束功率"
                  @input="limitDecimalPlaces(scope.row, 'end_power')"
                >
                  <template slot="append">W</template>
                </el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="服务费">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.price"
                style="width: 240px;"
                maxlength="6"
                placeholder="请输入服务费"
                size="mini"
                @input="limitDecimalPlaces(scope.row, 'price')"
              >
                <template slot="append">元/时</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="120">
            <template slot-scope="scope">
              <i
                class="el-icon-delete"
                style="color: #f00;font-size: 16px;cursor: pointer;"
                @click="deleteItem(scope, 'service_fee')"
              />
            </template>
          </el-table-column>
        </el-table>

        <div class="title-row">
          <div class="com-line-title mb0">电费配置</div>
          <el-tooltip content="新增电费配置" placement="top">
            <i class="el-icon-circle-plus-outline icon" @click="addItem('charge_standard')" />
          </el-tooltip>
        </div>
        <el-table ref="table" :data="form.charge_standard">
          <el-table-column align="center" label="序号" width="120">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="时间段">
            <template slot-scope="scope">
              <div style="display: flex;justify-content: center;">
                <el-time-picker
                  v-model="scope.row.begin_time"
                  style="width: 240px;"
                  format="HH:mm"
                  value-format="HH:mm"
                  size="mini"
                  placeholder="开始时间"
                  @change="changeBeginTime(scope)"
                />
                <div style="margin: 0 10px;">-</div>
                <el-time-picker
                  :ref="`entTime${scope.$index}`"
                  v-model="scope.row.end_time"
                  style="width: 240px;"
                  size="mini"
                  format="HH:mm"
                  value-format="HH:mm"
                  placeholder="结束时间"
                />
              </div>
            </template>
          </el-table-column>
          <el-table-column align="center" label="电费">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.price"
                style="width: 240px;"
                maxlength="6"
                placeholder="请输入电费"
                size="mini"
                @input="limitDecimalPlaces(scope.row, 'price')"
              >
                <template slot="append">元/度</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="120">
            <template slot-scope="scope">
              <i
                class="el-icon-delete"
                style="color: #f00;font-size: 16px;cursor: pointer;"
                @click="deleteItem(scope, 'charge_standard')"
              />
            </template>
          </el-table-column>
        </el-table>

        <div class="title-row">
          <div class="com-line-title mb0">支付档位设置</div>
          <el-tooltip content="新增支付档位设置" placement="top">
            <i class="el-icon-circle-plus-outline icon" @click="addItem('prepay_list')" />
          </el-tooltip>
          <div class="switch-wrap">
            <div class="txt">
              充满自停
            </div>
            <el-switch
              v-model="form.auto_charge"
              :active-value="1"
              :inactive-value="0"
              active-color="#13ce66"
              inactive-color="#ccc"
            />
          </div>
        </div>
        <el-table :data="form.prepay_list">
          <el-table-column align="center" label="序号" width="120">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="金额">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.money"
                style="width: 400px;"
                maxlength="6"
                placeholder="请输入金额"
                size="mini"
                @input="limitDecimalPlaces(scope.row, 'money')"
              >
                <template slot="append">元</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="预计充电时长">
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.hours"
                style="width: 240px;"
                maxlength="6"
                placeholder="请输入预计充电时长"
                size="mini"
                @input="limitDecimalPlaces(scope.row, 'hours')"
              >
                <template slot="append">小时</template>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="120">
            <template slot-scope="scope">
              <i
                class="el-icon-delete"
                style="color: #f00;font-size: 16px;cursor: pointer;"
                @click="deleteItem(scope, 'prepay_list')"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
    </div>
  </div>
</template>

<script>
import { apiAddBillingStandard, apiEditBillingStandard, apiQueryBillingStandardDtl } from '@/api/billingCfg'
import LazyTree from '@/components/LazyTree'
import ComHeader from '@/common/components/ComHeader'

export default {
  components: {
    LazyTree,
    ComHeader
  },
  data() {
    return {
      rules: {
        charge_name: [{ required: true, message: '请输入收费标准名称', trigger: 'blur' }],
        shop_id: [{ required: true, message: '请选择门店', trigger: 'blur' }],
        charge_way: [{ required: true, message: '请选择计费类型', trigger: 'blur' }],
        service_fee_type: [{ required: true, message: '请选择服务费规则', trigger: 'blur' }],
        full_power: [{ required: true, message: '请输入满电功率', trigger: 'blur' }],
        over_power: [{ required: true, message: '请输入过载功率', trigger: 'blur' }],
        full_delay: [{ required: true, message: '请输入判满延时', trigger: 'blur' }],
        off_delay: [{ required: true, message: '请输入拔掉停充延时', trigger: 'blur' }]
      },
      isEdit: false,
      form: {
        charge_way: 2,
        service_fee: [],
        charge_standard: [],
        prepay_list: [],
        // service_fee_type: ['1'],
        refund_type: 1
      }
    }
  },
  beforeRouteLeave(to, from, next) {
    to.meta.refresh = true
    next()
  },
  computed: {
    title() {
      const { sn } = this.$route.query
      const title = sn ? '编辑费率设置' : '新增费率设置'
      return title
    }
  },
  created() {
    this._initData()
    // const title = this.title
    // this._setTagsViewTitle(title)
  },
  methods: {
    _setTagsViewTitle(title) {
      const route = Object.assign({}, this.$route, { title })
      this.$store.dispatch('updateVisitedView', route)
    },
    _initData() {
      const { sn } = this.$route.query
      if (!sn) return
      this.isEdit = true
      apiQueryBillingStandardDtl({ billing_standard_sn: sn }).then(res => {
        if (res.succeed) {
          const data = { ...res.body }
          if (Array.isArray(data.service_fee)) {
            data.service_fee.forEach(v => {
              v.price = ((v.price || 0) / 100)
            })
          }
          if (Array.isArray(data.charge_standard)) {
            data.charge_standard.forEach(v => {
              v.price = ((v.price || 0) / 100)
            })
          }
          if (Array.isArray(data.prepay_list)) {
            data.prepay_list.forEach(v => {
              v.money = ((v.money || 0) / 100)
            })
          }
          this.form = res.body
        }
      })
      // if (data) {
      //   const obj = JSON.parse(data)
      //   console.log(obj, 'obj')
      //   obj.service_fee_type = obj.service_fee_type.split(',')
      //   this.form = obj
      //   this.isEdit = true
      // }
    },
    // 限制只能输入两位小数
    limitDecimalPlaces(row, field) {
      if (row[field].includes('.')) {
        const parts = row[field].split('.')
        if (parts[1].length > 2) {
          parts[1] = parts[1].slice(0, 2)
          row[field] = parts.join('.')
        }
      }
    },
    changeBeginTime({ $index, row }) {
      this.$refs[`entTime${$index}`].focus()

      const [hours, minutes] = row.begin_time.split(':').map(Number)
      const beginDate = new Date()
      beginDate.setHours(hours, minutes, 0, 0)

      const endDate = new Date(beginDate.getTime() + 60 * 60 * 1000)
      const endTime = `${String(endDate.getHours()).padStart(2, '0')}:${String(endDate.getMinutes()).padStart(2, '0')}`

      this.$set(this.form.charge_standard[$index], 'end_time', endTime)
    },
    addItem(type) {
      this.form[type].push({})
    },
    deleteItem({ $index }, type) {
      this.form[type].splice($index, 1)
    },
    selectGroup(group) {
      this.$set(this.form, 'shop_id', group.shop_id)
      this.$set(this.form, 'shop_name', group.shop_name)
    },
    submit() {
      const request = this.isEdit ? apiEditBillingStandard : apiAddBillingStandard
      this.$refs.form.validate(valid => {
        if (!valid) return
        const form = JSON.parse(JSON.stringify(this.form))
        // if (form.service_fee_type) {
        //   form.service_fee_type = form.service_fee_type.join(',')
        // }
        if (!form.service_fee.length) {
          this.$message({ message: '服务费配置不能为空', type: 'warning' })
          return
        }
        if (!form.charge_standard.length) {
          this.$message({ message: '电费配置不能为空', type: 'warning' })
          return
        }
        if (!form.prepay_list.length) {
          this.$message({ message: '支付档位设置不能为空', type: 'warning' })
          return
        }
        form.service_fee.forEach(v => {
          v.price = ((v.price || 0) * 100)
        })
        form.charge_standard.forEach(v => {
          v.price = ((v.price || 0) * 100)
        })
        form.prepay_list.forEach(v => {
          v.money = ((v.money || 0) * 100)
        })
        request(form).then(res => {
          const { code } = res.data
          if (code === 200) {
            this.$message({
              message: '操作成功',
              type: 'success'
            })
            this.$router.go(-1)
          } else {
            this.$message({
              message: res.data.msg,
              type: 'error'
            })
          }
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.container {
  background: #F0F4F7;
}
.form {
    padding: 20px 14px;
    overflow: auto;
    background: #fff;
    height: calc(100vh - 150px);
}
.title-row {
    display: flex;
    align-items: center;
    margin: 12px 0;
}
.icon {
    font-size: 20px;
    color: #409EFF;
    cursor: pointer;
}
.cfg-row {
    display: flex;
    .input {
        width: 300px;
    }
}
.submit-btn {
    cursor: pointer;
    color: #409EFF;
    padding: 15px;
    text-align: center;
    border: 1px solid #409EFF;
    &:active {
        opacity: .6;
    }
}
.switch-wrap {
    font-size: 14px;
    display: flex;
    align-items: center;
    margin-left: 10px;
    .txt {
        margin-right: 8px;
    }
}
</style>
