<!-- eslint-disable camelcase -->
<template>
  <div class="policyForm" ref="policyForm">
    <div class="title">
      <div>基础信息</div>
      <img src="@/assets/images/titleLine.png" alt="" />
    </div>
    <a-form
      :model="formData"
      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'">
          <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="col2" required>
        <a-input-number
          :precision="2"
          v-model:value="formData.price[0]"
          suffix="元/kWh"
          :disabled="formStatus == 'read'"
          :min="0"
          addon-after="元/kWh"
        />
      </a-form-item>

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

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

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

      <a-form-item label="时段表" class="col1" v-if="formData.type == '1'">
        <a-table
          :columns="columns"
          :data-source="formData.period1"
          size="small"
          :scroll="{ y: 200 }"
          :pagination="false"
          row-class-name="no-hover-row"
          row-key="month"
          :expanded-row-keys="[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]"
        >
          <template #headerCell="{ column }">
            <template v-if="column.key === 'action'">
              <span>
                
                <PlusOutlined
                  @click="handleAdd"
                  :style="{ cursor: formStatus == 'read' ? 'not-allowed' : 'pointer' }"
                />
              </span>
            </template>
          </template>
          <template #bodyCell="{ column, index }">
            <template v-if="column.dataIndex === 'action'">
              <span>
                <a
                  @click="delPeriod(index)"
                  :style="{ cursor: formStatus == 'read' ? 'not-allowed' : 'pointer' }"
                  >删除</a
                >
              </span>
            </template>
          </template>
        </a-table>
      </a-form-item>
      <div v-if="formData.type == 5">
        <a-form-item label="充放策略" class="col1" name="chargePolicy">
          <a-radio-group
            v-model:value="formData.chargePolicy"
            :disabled="formStatus == 'read'"
            name="chargePolicy"
            @change="changePolicy"
          >
            <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.period5" :key="index">
              <span>第{{ index == 0 ? '一' : '二' }}次充放过程</span>
              <a-form
                :ref="
                  (el) => {
                    periodFormRefs[index] = el
                  }
                "
                :model="item"
                layout="inline"
                label-align="left"
                :label-col="{ style: { width: '85px' } }"
                :rules="periodRules"
              >
                <a-form-item label="充电时间" class="col2" name="charge_time">
                  <a-time-range-picker
                    format="HH:mm"
                    value-format="HH:mm"
                    :disabled="formStatus == 'read'"
                    v-model:value="formData.period5[index]['charge_time']"
                  />
                </a-form-item>

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

                <a-form-item label="充电功率" class="col2" name="chargeType">
                  <a-radio-group v-model:value="formData.period5[index].chargeType">
                    <div>
                      <a-radio :value="0">自动</a-radio>
                    </div>
                    <div>
                      <a-radio :value="1">自定义</a-radio>
                      <a-input
                        style="width: 120px"
                        v-model:value="formData.period5[index]['charge_power']"
                        suffix="kW"
                      ></a-input>
                    </div>
                  </a-radio-group>
                </a-form-item>

                <a-form-item label="放电功率" class="col2" name="dischargeType">
                  <a-radio-group v-model:value="formData.period5[index].dischargeType">
                    <div>
                      <a-radio :value="0">自动</a-radio>
                    </div>
                    <div>
                      <a-radio :value="1">自定义</a-radio>
                      <a-input
                        style="width: 120px"
                        v-model:value="formData.period5[index]['discharge_power']"
                        suffix="kW"
                      ></a-input>
                    </div>
                  </a-radio-group>
                </a-form-item>
              </a-form>
            </div>
          </div>
        </a-form-item>
      </div>

      <a-form-item label="策略描述" class="col1">
        <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" :disabled="formStatus == 'read'"
            >确认</a-button
          >
        </div>
      </a-form-item>
    </a-form>
  </div>
  <a-modal
    v-model:open="periodModal"
    @ok="handlePeriodModalOk"
    :get-container="() => $refs.policyForm"
  >
    <a-form
      ref="periodRef"
      :model="periodForm"
      :label-col="{ style: { width: '85px' } }"
      :rules="rules"
    >
      <a-form-item ref="name" label="月份" name="month" required>
        <a-select ref="select" v-model:value="periodForm.month" @change="selectMonth">
          <a-select-option v-for="item in 12" :value="item">{{ item }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="开始时间" name="time" required>
        <a-time-picker
          v-model:value="periodForm.time"
          value-format="HH:mm"
          format="HH:mm"
          :disabled-time="disabledTimeConfig"
        />
      </a-form-item>
      <a-form-item label="时段类型" name="type" required>
        <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-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'
    }
  },
  emits: ['closeModal'],
  data() {
    return {
      data: [],
      policyTypes,
      formData: {
        period1: [],
        period5: []
      },
      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'
          }
        ],
        month: [{ required: true, message: '请输入名称', trigger: 'change' }],
        time: [{ required: true, message: '请输入名称', trigger: 'change' }]
      },
      periodRules: {
        charge_time: [{ required: true, trigger: 'change' }],
        discharge_time: [{ required: true, trigger: 'change' }],
        chargeType: [{ required: true, trigger: 'change' }],
        dischargeType: [{ required: true, trigger: 'change' }]
      },
      periodFormRefs: [],
      disabledHours: [],
      disabledMinutes: []
    }
  },
  watch: {
    formState: {
      handler(newVal) {
        if (this.formStatus == 'add') {
          this.formData = {
            type: '',
            name: '',
            price: [0, 0, 0, 0],
            period1: [],
            period5: [
              {
                charge_time: [],
                discharge_time: [],
                charge_power: '',
                discharge_power: '',
                chargeType: null,
                dischargeType: null
              }
            ],
            is_open: false,
            chargePolicy: 1
          }
        } else {
          this.getFormData(newVal)
        }
      },
      deep: true, // 深度监听
      immediate: true
    }
  },
  mounted() {},
  methods: {
    disabledTimeConfig() {
      const that = this
      return {
        disabledHours: () => that.disabledHours.map((item) => Number(item)), // 禁用点
        disabledMinutes: () => that.disabledMinutes.map((item) => Number(item)),
        disabledSeconds: () => []
      }
    },
    splitAndDedupeTimeArray(times) {
      const hours = times.map((time) => {
        const [hour] = time.split(':')
        return parseInt(hour, 10)
      })

      const minutes = times.map((time) => {
        const [, minute] = time.split(':')
        return parseInt(minute, 10)
      })

      return {
        hours: [...new Set(hours)],
        minutes: [...new Set(minutes)]
      }
    },
    selectMonth(val) {
      let arr = []
      const res = this.formData.period1.find((item) => item.month == val) || null

      if (res) {
        if (res.children && res.children.length > 0) {
          arr = [res, ...res.children].map((item) => item.time)
        } else {
          arr = [res.time]
        }
      }
      const { hours, minutes } = this.splitAndDedupeTimeArray(arr)
      this.disabledHours = hours
      this.disabledMinutes = minutes
    },
    changePolicy(e) {
      const val = e.target.value
      console.log(val)

      if (val == 1) {

        this.formData.period5.splice(0, 1)
        this.formData.period1 = []
      } else {
        this.formData.period5[1] = {
          charge_time: [],
          discharge_time: [],
          charge_power: '',
          discharge_power: '',
          chargeType: null,
          dischargeType: null
        }
      }
    },
    //提交表单
    async handleOk() {
      const { type, price, is_open, chargePolicy } = this.formData
      const periodKey = `period${type}`
      const period = this.formData[periodKey] // 正确使用 period
      const newForm = { ...this.formData, is_open: Number(is_open) }

      if (type == 1) {
        const data = {
          period: this.getPeriodJson(type, period),
          price: price.map((item) => Number(item).toFixed(2))
        }

        newForm.value = JSON.stringify(data)
        delete newForm.period1
      } else {
        const data = {
          period: this.getPeriodJson(type, period.slice(0, chargePolicy)),
          price: price.map((item) => Number(item).toFixed(2))
        }
        newForm.value = JSON.stringify(data)
        delete newForm.period5
      }
      delete newForm.price
      

      this.validateform(newForm)
    },
    async validateform(newForm) {
      try {
        await this.$refs.formRef.validateFields()
        if (newForm.type == 5) {
          const validFormRefs = this.periodFormRefs.filter(
            (item) => item && typeof item.validateFields === 'function'
          )
          await Promise.all(validFormRefs.map((item) => item.validateFields()))
        }

        if (this.formStatus == 'add') {
          this.addPolicy(newForm)
        } else if (this.formStatus == 'edit') {
          this.updatePolicy(newForm)
        }
      } catch (error) {
        console.log(error)
      }
    },
    handleCancel() {
      this.$emit('closeModal')
    },
    async addPolicy(newForm) {
      try {
        const res = await postReq('/insertPolicy', newForm)
        if (res.errcode == 0) {
          this.$message.success('添加成功')
          this.$emit('closeModal', true)
        }
        console.log(res)
      } catch (error) {
        console.log(error)
      }
    },
    async updatePolicy(newForm) {
      try {
        const res = await postReq('/updatePolicy', newForm)
        if (res.errcode == 0) {
          this.$message.success('更新成功')
          this.$emit('closeModal', true)
        }
        console.log(res)
      } catch (error) {
        console.log(error)
      }
    },
    //时段表删除
    delPeriod(index) {
      this.formData.period1.splice(index, 1)
    },

    //获取编辑的表单
    getFormData(newVal) {
      const { value, type } = newVal

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

      this.formData = {
        ...newVal,
        is_open: Boolean(newVal['is_open']),
        price
      }
      this.formData[`period${type}`] = this.getPeriod(type, period)
    },
    handleAdd() {
      if (this.formStatus == 'read') return
      this.periodModal = true
      this.periodForm = {}
    },
    handlePeriodModalOk() {
      this.$refs.periodRef
        .validateFields()
        .then((res) => {
          const targetIndex = this.formData.period1.findIndex(
            (item) => item.month == this.periodForm.month
          )

          if (targetIndex !== -1) {
            // 如果找到，获取目标对象
            const target = this.formData.period1[targetIndex]

            // 创建所有项目的副本，避免循环引用
            const allItems = [
              { ...target },
              ...target.children.map((child) => ({ ...child,month:target.month })),
              { ...this.periodForm }
            ]

            // 按时间排序
            allItems.sort((a, b) => {
              return a.time.localeCompare(b.time)
            })

            // 排序后第一个作为新的父级元素
            const newTarget = allItems[0]
            // 其余元素作为children
            newTarget.children = allItems.slice(1).map((item) => {
              // 确保children中的项目不包含month属性
              const { month,children, ...rest } = item
              return rest
            })

            // 替换原数组中的元素
            this.formData.period1.splice(targetIndex, 1, newTarget)
          } else {
            // 如果未找到，创建新记录
            this.formData.period1.push({
              ...this.periodForm,
              children: []
            })
          }

          this.periodModal = false
        })
        .catch((err) => {
          console.log(err)
        })
    },
    getPeriod(type, list = []) {
      let newValue = []

      if (type == 1) {
        list.forEach((arr, index) => {
          if (arr.length == 0) return
          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 {
        this.formData.chargePolicy = list.length
        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)
        })
      }
      console.log(newValue, '==========')

      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])
          if (item.children.length > 0) {
            item.children.forEach((ele) => {
              newPeriod[month - 1].push([ele.time, ele.type])
            })
          }
        })
      } else {
        period.forEach((item, index) => {
          const ele = {
            ...item
          }
          delete ele.chargeType
          delete ele.dischargeType
          newPeriod.push(ele)
        })
      }
      return 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 {
  display: flex;
  flex-wrap: wrap;

  .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;
      margin-bottom: 10px;
    }
  }
}
.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,
  .ant-input-number-group,
  :deep(.ant-input-number-wrapper) {
    width: 200px;
  }
  :deep(.ant-input-number-group .ant-input-number-group-addon) {
    color: #fff;
    border: 1px solid $border-color;
  }
  textarea {
    .ant-input {
      width: 100%;
    }
  }
  .col2 {
    width: 50%;
  }
  .col4 {
    width: 25%;
    min-width: 270px;
  }
  .col1 {
    width: 100%;
    :deep(textarea.ant-input) {
      width: 100% !important;
    }
  }
}
:deep(.ant-table-wrapper .ant-table-row-expand-icon) {
  color: $green !important;
}
//表格行悬浮样式
:deep(.no-hover-row:hover > td) {
  background-color: transparent !important;
}
:deep(.ant-table-wrapper .ant-table-cell) {
  background: none !important;
}
:deep(.ant-table-cell) {
  &::before {
    width: 0 !important;
  }
}
</style>
