<!-- eslint-disable camelcase -->
<template>
  <div class="policyForm">
    <div class="title">
      <div>基础信息{{ formStatus }}</div>
      <img src="@/assets/images/titleLine.png" alt="" />
    </div>
    <a-form
      :model="formState"
      layout="inline"
      label-align="left"
      :label-col="{ style: { width: '85px' } }"
      :rules="rules"
      ref="formRef"
    >
      <a-form-item label="名称" class="col2" name="name">
        <a-input v-model:value="formData.name" :disabled="formStatus == 'read'" />
      </a-form-item>

      <a-form-item label="类型" class="col2" name="type">
        <a-select
          v-model:value="formData.type"
          placeholder=""
          :disabled="formStatus == 'read'"
          @change="changePolicy"
        >
          <a-select-option v-for="item in policyTypes" :value="item.value">{{
            item.label
          }}</a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item label="低谷电价" class="col4" required>
        <a-input-number
          :precision="2"
          v-model:value="formData.price[0]"
          suffix="元/kWh"
          :disabled="formStatus == 'read'"
        />
      </a-form-item>

      <a-form-item label="平段电价" class="col4" required>
        <a-input-number
          :precision="2"
          v-model:value="formData.price[1]"
          suffix="元/kWh"
          :disabled="formStatus == 'read'"
        />
      </a-form-item>

      <a-form-item label="高峰电价" class="col4" required>
        <a-input-number
          :precision="2"
          v-model:value="formData.price[2]"
          suffix="元/kWh"
          :disabled="formStatus == 'read'"
        />
      </a-form-item>

      <a-form-item label="尖峰电价" class="col4" required>
        <a-input-number
          :precision="2"
          v-model:value="formData.price[3]"
          suffix="元/kWh"
          :disabled="formStatus == 'read'"
        />
      </a-form-item>

      <a-form-item label="时段表" class="col1" v-if="formData.type == '1'">
        <a-table
          :columns="columns"
          :data-source="formData.period"
          size="small"
          :scroll="{ y: 500 }"
          :pagination="false"
        >
          <template #headerCell="{ column }">
            <template v-if="column.key === 'action'">
              <span>
                <!-- <a-button type="primary" @click="handleAdd" :disabled="formStatus == 'read'">Add</a-button> -->
                <i
                  class="iconfont icon-add"
                  @click="handleAdd"
                  :disabled="formStatus == 'read'"
                  style="cursor: pointer"
                ></i>
              </span>
            </template>
          </template>
          <template #bodyCell="{ column, record }">
            <template v-if="column.dataIndex === 'action'">
              <span>
                <a @click="edit(record.key)">操作</a>
              </span>
            </template>
          </template>
        </a-table>
      </a-form-item>
      <div v-if="formData.type == 5">
        <a-form-item label="充放策略" class="col1">
          <a-radio-group
            v-model:value="formData.chargePolicy"
            :disabled="formStatus == 'read'"
            name="chargePolicy"
          >
            <a-radio :value="1">一充一放</a-radio>
            <a-radio :value="2">两充两放</a-radio>
          </a-radio-group>
        </a-form-item>
        <a-form-item label="" class="col1">
          <div class="charge">
            <div class="box" v-for="(item, index) in formData.chargePolicy" :key="index">
              <span>第{{ index == 0 ? '一' : '二' }}次充放过程</span>
              <a-form
                :ref="'period' + index"
                :model="formData.period"
                layout="inline"
                label-align="left"
                :label-col="{ style: { width: '85px' } }"
                :rules="periodRules"
              >
                <a-form-item label="充电时间" class="col2" required>
                  <a-time-range-picker
                    v-model:value="formData.period[index]['charge_time']"
                    format="HH:mm"
                    value-format="HH:mm"
                    :disabled="formStatus == 'read'"
                  />
                </a-form-item>

                <a-form-item label="放电时间" class="col2" required>
                  <a-time-range-picker
                    v-model:value="formData.period[index]['discharge_time']"
                    format="HH:mm"
                    value-format="HH:mm"
                    :disabled="formStatus == 'read'"
                  />
                </a-form-item>

                <a-form-item label="充电功率" class="col2" required>
                  <a-radio-group
                    v-model:value="formData.period[index].chargeType"
                    :disabled="formStatus == 'read'"
                  >
                    <a-radio :value="0">自动</a-radio>
                    <a-radio :value="1">自定义</a-radio>
                    <a-input
                      style="width: 60px"
                      v-model:value="formData.period[index]['charge_power']"
                    ></a-input>
                  </a-radio-group>
                </a-form-item>

                <a-form-item label="放电功率" class="col2" required>
                  <a-radio-group
                    v-model:value="formData.period[index].dischargeType"
                    :disabled="formStatus == 'read'"
                  >
                    <a-radio :value="0">自动</a-radio>
                    <a-radio :value="1">自定义</a-radio>
                    <a-input
                      style="width: 60px"
                      v-model:value="formData.period[index]['discharge_power']"
                    ></a-input>
                  </a-radio-group>
                </a-form-item>
              </a-form>
            </div>
          </div>
        </a-form-item>
      </div>

      <a-form-item label="策略描述" class="col2">
        <a-textarea v-model:value="formData.describe" :disabled="formStatus == 'read'" />
      </a-form-item>
      <a-form-item label="是否启用" class="col2">
        <a-switch v-model:checked="formData['is_open']" :disabled="formStatus == 'read'" />
      </a-form-item>
      <a-form-item class="col1">
        <div style="display: flex; justify-content: center; gap: 20px">
          <a-button @click="handleCancel">取消</a-button>
          <a-button @click="handleOk" type="primary">确认</a-button>
        </div>
      </a-form-item>
    </a-form>
  </div>
  <a-modal v-model:open="periodModal" @ok="handlePeriodModalOk">
    <a-form ref="formRef" :model="periodForm" :label-col="{ style: { width: '85px' } }">
      <a-form-item ref="name" label="月份" name="month">
        <a-input v-model:value="periodForm.month" />
      </a-form-item>
      <a-form-item label="开始时间" name="time">
        <a-time-picker v-model:value="periodForm.time" value-format="HH:mm" format="HH:mm" />
      </a-form-item>
      <a-form-item label="时段类型" name="type">
        <a-select ref="select" v-model:value="periodForm.type">
          <a-select-option value="尖">尖</a-select-option>
          <a-select-option value="峰">峰</a-select-option>
          <a-select-option value="平">平</a-select-option>
          <a-select-option value="谷">谷</a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script>
import { policyTypes } from '@/utils/config'
import { postReq, getReq } from '@/request/api'
export default {
  name: '',
  components: {},
  props: {
    formState: {
      type: Object,
      default: () => {
        return {
          name: '',
          type: '',
          desc: ''
        }
      }
    },
    formStatus: {
      type: String,
      default: 'add'
    }
  },
  data() {
    return {
      data: [],
      policyTypes,
      formData: {},
      columns: [
        {
          title: '月份',
          dataIndex: 'month',
          key: 'month'
        },
        {
          title: '开始时间',
          dataIndex: 'time',
          key: 'time'
        },
        {
          title: '时段类型',
          dataIndex: 'type',
          key: 'type'
        },
        {
          title: '操作',
          dataIndex: 'action',
          key: 'action'
        }
      ],
      periodModal: false,
      periodForm: {},
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        type: [{ required: true, message: '请选择类型', trigger: 'change' }],
        price: [
          {
            type: 'array',
            required: true,
            message: '请输入电价',
            trigger: 'change'
          }
        ],
        period: [
          {
            type: 'array',
            required: true,
            message: '请选择时段',
            trigger: 'change'
          }
        ]
      },
      periodRules: {
        chargeTime: [{ required: true, trigger: 'change' }],
        dischargeTime: [{ required: true, trigger: 'change' }],
        chargeType: [{ required: true, trigger: 'change' }],
        dischargeType: [{ required: true, trigger: 'change' }]
      }
    }
  },
  watch: {
    formState: {
      handler(newVal) {
        if (this.formStatus == 'add') {
          this.formData = {
            type: '1',
            name: '测试',
            price: [0, 0, 0, 0],
            period: [],
            is_open: false,
            chargePolicy: 1
          }
          // this.formData = {
          //   type: '5',
          //   name: '测试',
          //   price: [0, 0, 0, 0],
          //   chargePolicy:1,//1从
          //   period: [{
          //     charge_time: [],
          //     discharge_time: [],
          //     charge_power: '',
          //     discharge_power: '',
          //     chargeType: 1,
          //     dischargeType:1
          //   },
          //   {
          //     charge_time: [],
          //     discharge_time: [],
          //     charge_power: '',
          //     discharge_power: '',
          //     chargeType: 1,
          //     dischargeType:1
          //   }
          //   ],
          //   is_open: false,
          //   chargePolicy:1
          // }
        } else {
          this.getFormData(newVal)
        }
      },
      deep: true, // 深度监听
      immediate: true
    }
  },
  mounted() {},
  methods: {
    changePolicy(val) {
      console.log(val)
      if (val == 1) {
        this.formData.period = []
      } else {
        this.formData.period = [
          {
            charge_time: [],
            discharge_time: [],
            charge_power: '',
            discharge_power: '',
            powerType: 1
          },
          {
            charge_time: [''],
            discharge_time: [''],
            charge_power: '',
            discharge_power: '',
            powerType: 1
          }
        ]
      }
    },
    //提交表单
    handleOk() {
      const { name, type, price, is_open, period, chargePolicy } = this.formData
      const newForm = { name, type, is_open }
      if (type == 1) {
        newForm.value = JSON.stringify({
          period: this.getPeriodJson(type, period),
          price: price.map((item) => Number(item))
        })
      } else {
        newForm.value = JSON.stringify({
          period: this.getPeriodJson(type, period.slice(0, chargePolicy)),
          price: price.map((item) => Number(item))
        })
      }
      console.log(newForm, 'this.formData')
      this.addPolicy(newForm)
    },
    handleCancel() {
      this.$emit('closeModal')
    },
    async addPolicy(newForm) {
      try {
        const res = await postReq('/insertPolicy', newForm)
        console.log(res)
      } catch (error) {
        console.log(error)
      }
    },

    //获取编辑的表单
    getFormData(newVal) {

      const { value, type } = newVal
      const { price, period } = JSON.parse(value)

      this.formData = {
        ...newVal,
        is_open: Boolean(newVal['is_open']),
        price,
        period: this.getPeriod(type, period)
      }
    },
    handleAdd() {
      this.periodModal = true
      this.periodForm = {}
    },
    handlePeriodModalOk() {
      this.formData.period.push(this.periodForm)
      this.periodModal = false
    },
    getPeriod(type, list=[]) {
      let newValue = []
      debugger
      if (type == 1) {
        list.forEach((arr, index) => {
          const item = arr[0]
          newValue.push({
            month: index + 1,
            time: item[0]||'',
            type: item[1]||'',
            children: []
          })
          for (let i = 1; i < arr.length; i++) {
            const element = arr[i]
            newValue[index].children.push({
              time: element[0]||'',
              type: element[1]||''
            })
          }
        })
      } else {
        list.forEach((item, index) => {
          const ele = {
            ...item,
            chargeType: item['charge_power'].length == 0 ? 0 : 1,
            dischargeType: item['discharge_power'].length == 0 ? 0 : 1
          }
          newValue.push(ele)
        })
      }
      return newValue
    },
    getPeriodJson(type, period) {
      let newPeriod = []

      if (type == 1) {
        newPeriod = Array.from({ length: 12 }, () => [])
        period.forEach((item, index) => {
          const { month, time, type } = item
          newPeriod[month - 1].push([time, type])
        })
      } else {
        period.forEach((item, index) => {
          const ele = {
            ...item
          }
          delete ele.chargeType
          delete ele.dischargeType
          newPeriod.push(ele)
        })
      }
      return JSON.stringify(newPeriod)
    }
  }
}
</script>

<style lang="scss" scoped>
.policyForm {
  color: #fff;
  .title {
    display: flex;
    font-weight: 700;
    flex-direction: column;

    img {
      width: 232px;
      height: 6px;
      margin-top: 10px;
    }
  }
}
.ant-form {
  .charge {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 10px;
    .box {
      border: 1px solid $table-border;
      padding-left: 10px;
      padding-top: 10px;
      padding-bottom: 10px;
      border-radius: 10px;
      color: #fff;
    }
  }
}
.ant-form-item {
  margin-inline-end: 0 !important;
  margin-top: 15px;
  :deep(.ant-form-item-label) {
    margin-left: 10px;
  }
}
.ant-form {
  .ant-form-item-label {
    > label {
      color: #fff;
    }
  }

  :deep(.ant-row) {
    width: 100%;
  }
  input,
  .ant-picker,
  .ant-select,
  .ant-input-affix-wrapper,
  .ant-input-number {
    width: 150px;
  }
  textarea {
    .ant-input {
      width: 100%;
    }
  }
  .col2 {
    width: 50%;
  }
  .col4 {
    width: 25%;
  }
  .col1 {
    width: 100%;
    :deep(textarea.ant-input) {
      width: 100% !important;
    }
  }
}
:deep(.ant-form-item-row) {
  // border: 1px solid red;
}
</style>
