<!--
@name: 时间计费策略-编辑页
@author: 张泽贤
@time: 2022-08-02
@doc: 
-->
<template>
  <p-spin :spinning="spinning">
    <p-card>
      <a-space slot="title" style="display: flex; align-items: center; cursor: pointer">
        <a-icon type="arrow-left" style="color: #1990ff" @click="back" />
        时间计费策略-{{ typeTitle }}
      </a-space>
      <div slot="extra" v-show="type !== 'view'">
        <p-button type="primary" @click="onSave">保存</p-button>
      </div>
    </p-card>
    <p-card>
      <p-form-model ref="ruleForm" class="plg-grid-from" :model="form" :label-col="{ span: 8 }" :wrapper-col="{ span: 16 }" :rules="rules">
        <a-divider orientation="left">基本信息</a-divider>
        <a-row>
          <a-col :span="6">
            <p-form-model-item label="策略名称" prop="strategyName">
              <div v-if="type === 'view'">{{ form.strategyName }}</div>
              <p-input v-model="form.strategyName" :disabled="type === 'edit'" v-else />
            </p-form-model-item>
          </a-col>
          <a-col :span="12">
            <p-form-model-item label="备注" prop="memo" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
              <div v-if="type === 'view'">{{ form.memo }}</div>
              <p-input v-model="form.memo" v-else />
            </p-form-model-item>
          </a-col>
        </a-row>
        <a-divider orientation="left">计费规则</a-divider>
        <a-row>
          <a-col :span="6">
            <p-form-model-item label="开始时间" prop="startDate">
              <div v-if="type === 'view'">{{ form.startDateName }}</div>
              <p-select v-model="form.startDate" :options="options.OMS_START_DATE_STRATEGY" allowClear v-else />
            </p-form-model-item>
          </a-col>
          <a-col :span="6">
            <p-form-model-item label="结束时间" prop="endDate">
              <div v-if="type === 'view'">{{ form.endDateName }}</div>
              <p-select v-model="form.endDate" :options="options.OMS_END_DATE_STRATEGY" allowClear v-else />
            </p-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="6">
            <p-form-model-item label="时间精度" prop="timePrecision">
              <div v-if="type === 'view'">{{ form.timePrecision }}</div>
              <p-select v-model="form.timePrecision" :options="options.WEIGHT_PRECISION" @change="timePrecisionChange" v-else />
            </p-form-model-item>
          </a-col>
          <a-col :span="6">
            <p-form-model-item label="时间取整" prop="timeInteger">
              <div v-if="type === 'view'">{{ form.timeIntegerName }}</div>
              <p-select v-model="form.timeInteger" :options="options.WEIGHT_INTEGER" v-else />
            </p-form-model-item>
          </a-col>
        </a-row>
        <a-row>
          <a-col :span="6">
            <p-form-model-item label="" prop="timeLadderEnable">
              <p-checkbox v-model="form.timeLadderEnable" :readOnly="type === 'view'">是否启用阶梯时间换算</p-checkbox>
            </p-form-model-item>
          </a-col>
          <a-col :span="12">
            <p-form-model-item label="" prop="endDate" :label-col="{ span: 0 }" :wrapper-col="{ span: 24 }">
              <a-alert message="注意：n代表实际小时（结束时间 - 开始时间）" type="error" />
            </p-form-model-item>
          </a-col>
        </a-row>
        <!-- <a-row>
          <a-col :span="12">
            <p-form-model-item label="计费时效" prop="endDate" :label-col="{ span: 4 }" :wrapper-col="{ span: 20 }">
              <a-alert message="(结束时间 - 开始时间) * 24 【四舍五入2位小数】" type="info" />
            </p-form-model-item>
          </a-col>
        </a-row> -->
      </p-form-model>
      <div v-if="form.timeLadderEnable">
        <a-divider orientation="left">阶梯时间</a-divider>
        <p-card>
          <a-space slot="extra">
            <p-button type="primary" @clickSync="onTableAddBtn" v-if="type !== 'view'">新增</p-button>
            <p-button type="danger" @clickSync="onTableDeleteBtn" v-if="type !== 'view'" :disabled="!selectedRowKeys.length">删除</p-button>
          </a-space>
          <p-table
            ref="priceTable"
            dragle
            bordered
            row-key="id"
            :scroll="{ x: true, height: 300 }"
            :data-source.sync="ladderList"
            :rowSelectType="2"
            :selectedRowKeys.sync="selectedRowKeys"
            :autoLoad="false"
          >
            <p-table-column data-index="sectionDownSymbol" title="区间下限符号">
              <template slot-scope="text, record">
                <div v-if="type === 'view'">{{ record.sectionDownSymbolName }}</div>
                <p-select v-model="record.sectionDownSymbol" :options="options.SECTION_SYMBOL" style="width: 100%" v-else />
              </template>
            </p-table-column>
            <p-table-column data-index="sectionDown" title="区间下限(小时)">
              <template slot-scope="text, record">
                <div v-if="type === 'view'">{{ record.sectionDown }}</div>
                <p-input-number v-model="record.sectionDown" style="width: 100%" v-else />
              </template>
            </p-table-column>
            <p-table-column data-index="sectionUpSymbol" title="区间上限符号">
              <template slot-scope="text, record">
                <div v-if="type === 'view'">{{ record.sectionUpSymbolName }}</div>
                <p-select v-model="record.sectionUpSymbol" :options="options.LESS_THAN" style="width: 100%" v-else />
              </template>
            </p-table-column>
            <p-table-column data-index="sectionUp" title="区间上限(小时)">
              <template slot-scope="text, record">
                <div v-if="type === 'view'">{{ record.sectionUp }}</div>
                <p-input-number v-model="record.sectionUp" :min="record.sectionDown" style="width: 100%" v-else />
              </template>
            </p-table-column>
            <p-table-column data-index="ladderTime" title="计费时间(小时)">
              <template slot-scope="text, record">
                <div v-if="type === 'view'">{{ record.ladderTime }}</div>
                <p-input-number v-model="record.ladderTime" :min="0" :precision="form.timePrecision" style="width: 100%" v-else />
              </template>
            </p-table-column>
          </p-table>
        </p-card>
      </div>
    </p-card>
  </p-spin>
</template>

<script>
import { View, Save, Update } from '../js/api';

export default {
  props: {
    type: {
      type: String,
      default: '',
    },
    editId: {
      type: String,
      default: '',
    },
    options: {
      type: Object,
      default: () => ({}),
    },
  },
  computed: {
    typeTitle() {
      const dictionary = {
        add: '新增',
        edit: '编辑',
        view: '查看',
        copy: '复制',
      };
      return dictionary[this.type] || this.type;
    },
  },
  data() {
    return {
      spinning: false,

      form: {},
      rules: {
        strategyName: [{ required: true, message: '策略名称不能为空', trigger: 'blur' }],
        timePrecision: [{ required: true, message: '时间精度不能为空', trigger: 'change' }],
        timeInteger: [{ required: true, message: '时间取整不能为空', trigger: 'change' }],
      },

      // 阶梯时间
      ladderList: [],
      selectedRowKeys: [],
    };
  },
  mounted() {
    if (this.editId) {
      this.spinning = true;
      View({ id: this.editId })
        .then((res) => {
          if (res.success) {
            res.data.timeLadderEnable = res.data.timeLadderEnable === 1;
            this.form = { ...res.data };
            delete this.form.timeStrategyLadderDTOS;
            this.ladderList = res.data.timeStrategyLadderDTOS ? [...res.data.timeStrategyLadderDTOS] : [];
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    }
  },
  methods: {
    back() {
      this.$emit('back');
    },

    // 保存
    onSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) return;
        if (this.type === 'add' || this.type === 'copy') this.onMethod(Save);
        if (this.type === 'edit') this.onMethod(Update);

        return;
      });
    },
    onMethod(method) {
      let params = { ...this.form };
      params.timeLadderEnable = params.timeLadderEnable ? 1 : 0;
      if (params.timeLadderEnable === 1) {
        params.timeStrategyLadderVOS = this.ladderList.map((item) => {
          let reslut = { ...item };
          if (reslut.type === 'add') {
            delete reslut.type;
            delete reslut.id;
          }
          return reslut;
        });
      }

      this.spinning = true;
      method(params)
        .then((res) => {
          if (res.success) {
            this.$message.success(res.message);
            this.$emit('back');
          } else {
            this.$exception(res);
          }
        })
        .finally(() => {
          this.spinning = false;
        });
    },

    // ----------------------------------表格----------------------------------
    // 新增
    onTableAddBtn() {
      this.ladderList.push({
        id: new Date().getTime(),
        type: 'add',
        ladderTime: null,
        sectionDown: null,
        sectionDownSymbol: null,
        sectionUp: null,
        sectionUpSymbol: null,
      });
    },
    // 删除
    onTableDeleteBtn() {
      let list = [];
      this.ladderList.forEach((item) => {
        if (!this.selectedRowKeys.includes(item.id)) {
          list.push(item);
        }
      });
      this.ladderList = [...list];
      this.selectedRowKeys = [];
    },

    timePrecisionChange() {
      this.ladderList.forEach((item) => (item.ladderTime = null));
    },
  },
};
</script>

<style lang="less" scoped>
.border {
  border: 1px solid #e8e8e8;
}
</style>