<template>
  <div class="app-container">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="服务区用电" name="first">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAttrAdd" v-hasPermi="['basecfg:price:add']">新增
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" :search="false" @queryTable="getAttrList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="attrList">
          <el-table-column label="服务区" align="center" prop="areaName" />
          <el-table-column label="用电分类" align="center" prop="elecTypeName" />
          <el-table-column label="电压等级" align="center" prop="voltageLevel" />
          <el-table-column label="容(需)量策略" align="center">
            <el-table-column label="容(需）量类型" align="center" prop="reqCapacityFlag" :formatter="matchReqCapacityFlag" />
            <el-table-column label="变压器容量（千伏·安）" align="center" prop="transCapacity" />
            <el-table-column label="最大需量（千瓦）" align="center" prop="reqQuantity" />
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text"  icon="el-icon-edit" @click="handleAttrUpdate(scope.row)" v-hasPermi="['basecfg:price:edit']">
                修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" class="deleteBtn" @click="handleAttrDelete(scope.row)" v-hasPermi="['basecfg:price:remove']">
                删除</el-button>

            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryAttrParams.pageNum" :limit.sync="queryAttrParams.pageSize"
          @pagination="getAttrList" />
        <!-- 添加或修改服务区用电属性对话框 -->
        <el-dialog :title="title" :visible.sync="attrOpen" width="500px" append-to-body>
          <el-form ref="attrForm" :model="attrForm" :rules="attrRules" label-width="150px">
            <el-form-item label="园区" prop="areaCode">
              <el-select v-model="attrForm.areaCode" :disabled="title.includes('修改')">
                <el-option v-for="item in areaOptions" :label="item.label" :value="item.id" :key="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="价格策略" prop="priceCode">
              <el-select v-model="attrForm.priceCode">
                <el-option v-for="item in gwPriceOptions" :label="`${item.elecTypeName}&lt;${item.voltageLevel}&gt;`" :value="item.cfgCode"
                  :key="item.cfgCode" />
              </el-select>
            </el-form-item>
            <el-form-item label="容(需）量类型" prop="reqCapacityFlag">
              <el-select v-model="attrForm.reqCapacityFlag">
                <el-option v-for="item in reqCapacityOptions" :label="item.name" :value="item.code" :key="item.code" />
              </el-select>
            </el-form-item>
            <el-form-item label="变压器容量(kVA/月)" prop="transCapacity" v-if="attrForm.reqCapacityFlag === 1">
              <el-input v-model="attrForm.transCapacity" placeholder="请输入变压器容量" />
            </el-form-item>
            <el-form-item label="最大需量(kW·h/月)" prop="reqQuantity" v-if="attrForm.reqCapacityFlag === 2">
              <el-input v-model="attrForm.reqQuantity" placeholder="请输入最大需量" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitAttrForm">确 定</el-button>
            <el-button @click="attrCancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane label="国网电价" name="second">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleGwPriceAdd" v-hasPermi="['basecfg:price:add']">新增
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" :search="false" @queryTable="getGwPriceList"></right-toolbar>
        </el-row>
        <el-table v-loading="loading" :data="gwPriceList">
          <el-table-column label="用电分类" align="center" prop="elecTypeName" />
          <el-table-column label="电压等级" align="center" prop="voltageLevel" />
          <el-table-column label="电度用电价格" align="center" prop="degreePrice" />
          <el-table-column label="分时电度用电价格" align="center">
            <el-table-column label="尖峰时段" align="center" prop="fsPeakDegreePrice" />
            <el-table-column label="高峰时段" align="center" prop="fsHighDegreePrice" />
            <el-table-column label="平峰时段" align="center" prop="fsFlatDegreePrice" />
            <el-table-column label="低谷时段" align="center" prop="fsLowDegreePrice" />
          </el-table-column>
          <el-table-column label="容(需)量用电价格" align="center">
            <el-table-column label="最大需量 (元/千瓦时·月)" align="center" prop="maxReqPrice" width="80px" />
            <el-table-column label="变压器容量（元/千伏安·月）" align="center" prop="transCapacityPrice" width="80px" />
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text"  icon="el-icon-edit" @click="handleGwPriceUpdate(scope.row)" v-hasPermi="['basecfg:price:edit']">
                修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" class="deleteBtn" @click="handleGwPriceDelete(scope.row)" v-hasPermi="['basecfg:price:remove']">
                删除</el-button>

            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryGwPriceParams.pageNum" :limit.sync="queryGwPriceParams.pageSize"
          @pagination="getGwPriceList" />

        <!-- 添加或修改电价配置对话框 -->
        <el-dialog :title="title" :visible.sync="gwPriceCfgOpen" width="500px" append-to-body>
          <el-form ref="gwPriceForm" :model="gwPriceForm" :rules="gwPriceRules" label-width="150px">
            <el-form-item label="配置代码" prop="cfgCode">
              <el-input v-model="gwPriceForm.cfgCode" maxlength="4" placeholder="请输入配置代码" />
            </el-form-item>
            <el-form-item label="用电分类" prop="elecType">
              <el-select v-model="gwPriceForm.elecType">
                <el-option v-for="item in priceTypeOptions" :label="item.name" :value="item.code" :key="item.code" />
              </el-select>
            </el-form-item>
            <el-form-item label="电压等级" prop="voltageLevel">
              <el-input v-model="gwPriceForm.voltageLevel" placeholder="请输入电压等级" />
            </el-form-item>
            <el-form-item label="电度用电价格" prop="degreePrice">
              <el-input v-model="gwPriceForm.degreePrice" placeholder="请输入电度用电价格" />
            </el-form-item>
            <el-form-item label="尖峰时段价格" prop="fsPeakDegreePrice">
              <el-input v-model="gwPriceForm.fsPeakDegreePrice" placeholder="请输入分时尖峰时段价格" />
            </el-form-item>
            <el-form-item label="高峰时段价格" prop="fsHighDegreePrice">
              <el-input v-model="gwPriceForm.fsHighDegreePrice" placeholder="请输入分时高峰时段价格" />
            </el-form-item>
            <el-form-item label="平峰时段价格" prop="fsFlatDegreePrice">
              <el-input v-model="gwPriceForm.fsFlatDegreePrice" placeholder="请输入分时平峰时段价格" />
            </el-form-item>
            <el-form-item label="低谷时段价格" prop="fsLowDegreePrice">
              <el-input v-model="gwPriceForm.fsLowDegreePrice" placeholder="请输入分时低谷时段价格" />
            </el-form-item>
            <el-form-item label="最大需量用电价格" prop="maxReqPrice" v-if="gwPriceForm.elecType === 4">
              <el-input v-model="gwPriceForm.maxReqPrice" placeholder="请输入最大需量用电价格" />
            </el-form-item>
            <el-form-item label="变压器容量用电价格" prop="transCapacityPrice" v-if="gwPriceForm.elecType === 4">
              <el-input v-model="gwPriceForm.transCapacityPrice" placeholder="请输入变压器容量用电价格" />
            </el-form-item>
          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitGwPriceForm">确 定</el-button>
            <el-button @click="gwPriceCancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane label="光伏电价" name="third">
        <!-- 光伏电价配置 -->
        <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handlePvPriceAdd" v-hasPermi="['basecfg:price:add']">新增
            </el-button>
          </el-col> -->
          <right-toolbar :showSearch.sync="showSearch" :search="false" @queryTable="getPvPriceList"></right-toolbar>
        </el-row>
        <el-table v-loading="loading" :data="pvPriceList">
          <el-table-column label="价格名称" align="center" prop="priceName" />
          <el-table-column label="用户电价/脱硫煤电价" align="center" prop="objPrice" />
          <el-table-column label="国家补贴" align="center" prop="stateSubsidy" />
          <el-table-column label="地方补贴" align="center" prop="localSubsidy" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text"  icon="el-icon-edit" @click="handlePvPriceUpdate(scope.row)" v-hasPermi="['basecfg:price:edit']">
                修改</el-button>

            </template>
          </el-table-column>
        </el-table>

        <!-- 添加或修改电价配置对话框 -->
        <el-dialog :title="title" :visible.sync="pvPriceOpen" width="500px" append-to-body>
          <el-form ref="pvPriceForm" :model="pvPriceForm" :rules="pvPriceRules" label-width="150px">
            <el-form-item label="配置代码" prop="cfgCode">
              <el-input v-model="pvPriceForm.cfgCode" placeholder="请输入配置代码" />
            </el-form-item>
            <el-form-item label="价格名称" prop="priceName">
              <el-input v-model="pvPriceForm.priceName" placeholder="请输入价格名称" />
            </el-form-item>
            <el-form-item label="用户/脱硫煤电价" prop="objPrice">
              <el-input v-model="pvPriceForm.objPrice" placeholder="请输入价格" />
            </el-form-item>
            <el-form-item label="国家补贴" prop="stateSubsidy">
              <el-input v-model="pvPriceForm.stateSubsidy" placeholder="请输入国家补贴" />
            </el-form-item>
            <el-form-item label="地方补贴" prop="localSubsidy">
              <el-input v-model="pvPriceForm.localSubsidy" placeholder="请输入国家补贴" />
            </el-form-item>

          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitPvPriceForm">确 定</el-button>
            <el-button @click="pvPriceCancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane label="峰谷电价策略" name="fourth">
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleStrategyAdd" v-hasPermi="['basecfg:price:add']">新增
            </el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" :search="false" @queryTable="getStrategyList"></right-toolbar>
        </el-row>
        <el-table v-loading="strategyParams.loading" :data="strategyList">
          <el-table-column label="策略编码" align="center" prop="strategyCode" />
          <el-table-column label="策略名称" align="center" prop="strategyName" />
          <el-table-column label="执行日期" align="center" prop="repeatType">
            <template slot-scope="scope">
              {{formatDict(scope.row.repeatType,'repeatTypeOptions')}}
            </template>
          </el-table-column>
          <el-table-column label="执行说明" align="center" prop="repeatParam" />
          <el-table-column label="策略描述" align="center" prop="strategyDesc" show-overflow-tooltip />
          <el-table-column label="优先级" align="center" prop="priority" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-info"  v-if="scope.row.editFlag==0" @click="handleStrategyDetail(scope.row)" v-hasPermi="['basecfg:price:edit']">
                查看</el-button>
              <el-button size="mini" type="text"  icon="el-icon-edit"  v-else @click="handleStrategyUpdate(scope.row)" v-hasPermi="['basecfg:price:edit']">
                修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" class="deleteBtn" @click="handleStrategyDelete(scope.row)" v-hasPermi="['basecfg:price:remove']" :disabled="scope.row.editFlag==0">
                删除</el-button>

            </template>
          </el-table-column>
        </el-table>

        <!-- 添加或修改峰谷电价策略配置对话框 -->
        <el-dialog :title="title" :visible.sync="strategyDialog" width="750px" append-to-body>
          <el-form ref="strategyForm" class="strategyForm" :model="strategyForm" :disabled="ifDisabled" label-width="100px">
            <el-form-item label="策略编码" prop="strategyCode" required :rules="[{required:true,message:'策略编码不能为空'}]">
              <el-input v-model="strategyForm.strategyCode" placeholder="请输入策略编码" />
            </el-form-item>
            <el-form-item label="策略名称" prop="strategyName" required :rules="[{required:true,message:'策略编码不能为空'}]">
              <el-input v-model="strategyForm.strategyName" placeholder="请输入策略名称" />
            </el-form-item>
            <el-form-item label="执行日期" prop="repeatType" required :rules="[{required:true,message:'请选择执行日期'}]">
              <el-select v-model="strategyForm.repeatType" style="width:100%" placeholder="请选择执行日期" @change="repeatTypeChange">
                <el-option v-for="item in repeatTypeOptions" :label="item.name" :value="item.value" :key="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="执行说明" required :rules="[{required:true,message:'请选择执行说明'}]" prop="repeatParam"
                          v-if="[1,5,6].includes(strategyForm.repeatType)">
              <el-time-picker v-if="strategyForm.repeatType==1" v-model="strategyForm.repeatParam" value-format="HH:mm:ss"
                              :picker-options="{selectableRange: '00:00:00 - 23:59:59'}" placeholder="选择时间">
              </el-time-picker>
              <el-checkbox-group v-else-if="strategyForm.repeatType==5" v-model="strategyForm.repeatParam">
                <el-checkbox v-for="day in weeks.filter(item=>item.value<6)"  :label="day.value" :key="day.value">
                  {{day.name}}</el-checkbox>
              </el-checkbox-group>
              <el-checkbox-group v-else-if="strategyForm.repeatType==6" v-model="strategyForm.repeatParam">
                <el-checkbox v-for="day in weeks" :label="day.value" :key="day.value">{{day.name}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="策略描述" prop="strategyDesc">
              <el-input v-model="strategyForm.strategyDesc" placeholder="请输入策略描述" />
            </el-form-item>
            <el-form-item label="优先级" prop="priority" required>
              <el-input-number v-model="strategyForm.priority" :min="0" :max="100" label="描述文字"></el-input-number>
            </el-form-item>
            <el-form-item label="小时电价">
              <el-table class="sub-table" :data="strategyForm.hourList" max-height="200px">
                <el-table-column label="开始时刻" align="center" prop="startTime">
                  <template slot-scope="scope">
                    <el-time-picker v-model="scope.row.startTime" size="mini" value-format="HH:mm:ss"
                                    :picker-options="{selectableRange: '00:00:00 - 23:59:59'}" placeholder="选择时间">
                    </el-time-picker>
                  </template>
                </el-table-column>
                <el-table-column label="结束时刻" align="center" prop="endTime">
                  <template slot-scope="scope">
                    <el-time-picker v-model="scope.row.endTime" size="mini" value-format="HH:mm:ss"
                                    :picker-options="{selectableRange: '00:00:00 - 23:59:59'}" placeholder="选择时间">
                    </el-time-picker>
                  </template>
                </el-table-column>
                <el-table-column label="计量类型" align="center" prop="type">
                  <template slot-scope="scope">
                    <el-select v-model="scope.row.type" size="mini" style="width:100%" placeholder="请选择">
                      <el-option label="低谷电" :value="-1" />
                      <el-option label="平峰电" :value="0" />
                      <el-option label="高峰电" :value="1" />
                      <el-option label="尖峰电" :value="2" />
                    </el-select>
                  </template>
                </el-table-column>
                <el-table-column align="center" width="100" v-if="!ifDisabled">
                  <template slot="header">
                    <div class="operateBtns" @click="addSub">
                      <span>操作</span><i class="el-icon-circle-plus-outline"></i>
                    </div>
                  </template>
                  <template slot-scope="scope">
                    <i class="el-icon-delete" @click="deleteSub(scope.$index)"></i>
                  </template>
                </el-table-column>
              </el-table>
            </el-form-item>

          </el-form>
          <div slot="footer" class="dialog-footer" v-if="!ifDisabled">
            <el-button type="primary" @click="submitStrategyForm">确 定</el-button>
            <el-button @click="strategyCancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-tab-pane>
      <el-tab-pane label="商户计费配置" name="five">
        <!-- 商户计费配置 -->
        <el-row :gutter="10" class="mb8">
          <!-- <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleChargingAdd" v-hasPermi="['basecfg:price:add']">新增
            </el-button>
          </el-col> -->
          <right-toolbar :showSearch.sync="showSearch" :search="false" @queryTable="getChargingList"></right-toolbar>
        </el-row>
        <el-table v-loading="chargingParams.loading" :data="chargingList">
          <el-table-column label="服务区名称" align="center" prop="areaName" />
          <el-table-column label="电计量单价" align="center" prop="elecUnitPrice" />
          <el-table-column label="电公摊计算类型" align="center">
            <template slot-scope="scope">
              {{formatDict(scope.row.elecGtComputeType,'computeTypeOptions')}}
            </template>
          </el-table-column>
          <el-table-column label="电费计算说明" align="center" prop="elecComputeDesc" show-overflow-tooltip />
          <el-table-column label="水计量单价" align="center" prop="waterUnitPrice" />
          <el-table-column label="水公摊计量类型" align="center">
            <template slot-scope="scope">
              {{formatDict(scope.row.waterGtComputeType,'computeTypeOptions')}}
            </template>
          </el-table-column>
          <el-table-column label="水费说明" align="center" prop="waterComputeDesc" show-overflow-tooltip />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text"  icon="el-icon-edit" @click="handleChargingUpdate(scope.row)" v-hasPermi="['basecfg:price:edit']">
                修改</el-button>
              <!-- <el-button size="mini" type="text" icon="el-icon-delete" @click="handleChargingDelete(scope.row)"
                v-hasPermi="['basecfg:price:del']">删除</el-button> -->
            </template>
          </el-table-column>
        </el-table>

        <!-- 添加或修改对话框 -->
        <el-dialog :title="title" :visible.sync="chargingDialog" custom-class="custom-dialog" width="650px" append-to-body>
          <el-form ref="chargingForm" :model="chargingForm" label-width="120px">
            <el-form-item label="服务区名称" prop="areaCode" required :rules="[{required:true,message:'请选择服务区名称'}]">
              <el-select v-model="chargingForm.areaCode" disabled style="width:100%">
                <el-option v-for="item in areaOptions" :label="item.label" :value="item.id" :key="item.id" />
              </el-select>
            </el-form-item>
            <el-form-item label="电计量单价" prop="elecUnitPrice" required :rules="[{required:true,message:'电计量单价不能为空'}]">
              <el-input v-model="chargingForm.elecUnitPrice" oninput="value=value.replace(/[^\d.]/g,'')" placeholder="请输入电计量单价" />
            </el-form-item>
            <el-form-item label="电公摊计算类型" prop="elecGtComputeType" required :rules="[{required:true,message:'请选择电公摊计算类型'}]">
              <el-select v-model="chargingForm.elecGtComputeType" style="width:100%">
                <el-option v-for="item in computeTypeOptions" :label="item.name" :value="item.value" :key="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="电费计算说明" prop="elecComputeDesc">
              <el-input v-model="chargingForm.elecComputeDesc" placeholder="请输入电费计算说明" />
            </el-form-item>
            <el-form-item label="水计量单价" prop="waterUnitPrice" required :rules="[{required:true,message:'水计量单价不能为空'}]">
              <el-input v-model="chargingForm.waterUnitPrice" oninput="value=value.replace(/[^\d.]/g,'')" placeholder="请输入水计量单价" />
            </el-form-item>
            <el-form-item label="水公摊计算类型" prop="waterGtComputeType" required :rules="[{required:true,message:'请选择水公摊计算类型'}]">
              <el-select v-model="chargingForm.waterGtComputeType" style="width:100%">
                <el-option v-for="item in computeTypeOptions" :label="item.name" :value="item.value" :key="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="水费说明" prop="waterComputeDesc">
              <el-input v-model="chargingForm.waterComputeDesc" placeholder="请输入水费说明" />
            </el-form-item>
            <el-form-item label="关联商户" prop="waterComputeDesc">
              <el-checkbox-group v-model="chargingForm.relCoList" class="custom-checkbox-group">
                <el-checkbox v-for="item in zoningList" :key="item.zoningCode" :label="item.zoningCode">{{item.zoningName}}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

          </el-form>
          <div slot="footer" class="dialog-footer">
            <el-button type="primary" @click="submitChargingForm">确 定</el-button>
            <el-button @click="chargingCancel">取 消</el-button>
          </div>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>

  </div>
</template>

<script>
import {
  listAttr,
  getAttr,
  delAttr,
  addAttr,
  updateAttr,
  listStrategy,
  addStrategy,
  updateStrategy,
  delStrategy,
  listCharging,
  updateCharging,
  addCharging,
  delCharging
} from '@/api/basecfg/elecAttr'
import {
  listGwPriceConfig,
  listGwPriceConfigAll,
  getGwPriceConfig,
  addGwPriceConfig,
  delGwPriceConfig,
  updateGwPriceConfig
} from '@/api/basecfg/elecGwPrice'
import { addPvPriceConfig, delPvPriceConfig, getPvPriceConfig, listPvPriceConfig, updatePvPriceConfig } from '@/api/basecfg/elecPvPrice'
import { getElecPriceType } from '@/api/commonApi'
import { areaTreeSelect } from '@/api/basecfg/area'
import { listZoning } from '@/api/basecfg/zoning'

export default {
  name: 'Attr',
  data() {
    return {
      activeTab: 'first',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 服务区用电属性表格数据
      attrList: [],
      // 电价表格
      gwPriceList: [],
      // 光伏电价
      pvPriceList: [],
      // 峰谷电价
      strategyList: [],
      // 商户计费
      chargingList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      attrOpen: false,
      gwPriceCfgOpen: false,
      pvPriceOpen: false,
      strategyDialog: false,
      chargingDialog: false,
      // 选项定义
      priceTypeOptions: undefined,
      areaOptions: undefined,
      gwPriceOptions: undefined,
      // 查询参数
      queryGwPriceParams: {
        pageNum: 1,
        pageSize: 10
      },
      queryAttrParams: {
        pageNum: 1,
        pageSize: 10
      },
      queryPvPriceParams: {
        pageNum: 1,
        pageSize: 10
      },
      strategyParams: {
        loading: false,
        pageNum: 1,
        pageSize: 10
      },
      chargingParams: {
        loading: false,
        pageNum: 1,
        pageSize: 10
      },
      // 表单参数
      attrForm: {},
      gwPriceForm: {},
      pvPriceForm: {},
      // 表单校验
      gwPriceRules: {
        cfgCode: [{ required: true, message: '配置代码不为空', trigger: 'blur' }],
        elecType: [{ required: true, message: '请选择用电分类', trigger: 'change' }],
        voltageLevel: [{ required: true, message: '电压等级不为空', trigger: 'blur' }]
      },
      // 表单校验
      attrRules: {
        areaCode: [{ required: true, message: '园区代码不能为空', trigger: 'blur' }],
        elecType: [{ required: true, message: '请选择用电分类', trigger: 'change' }],
        priceCode: [{ required: true, message: '价格编码不能为空', trigger: 'blur' }]
      },
      // 表单校验
      pvPriceRules: {
        cfgCode: [{ required: true, message: '配置代码不为空', trigger: 'blur' }],
        priceName: [{ required: true, message: '价格名称不为空', trigger: 'blur' }]
      },
      reqCapacityOptions: [
        { code: 0, name: '不涉及' },
        { code: 1, name: '容量电价' },
        { code: 2, name: '需量电价' }
      ],
      repeatTypeOptions: [
        { name: '执行1次', value: 1 },
        { name: '每天', value: 2 },
        { name: '法定工作日（跳过节假日）', value: 3 },
        { name: '法定节假日（跳过工作日）', value: 4 },
        { name: '周一至周五', value: 5 },
        { name: '自定义', value: 6 }
      ],
      weeks: [
        { name: '周一', value: '1' },
        { name: '周二', value: '2' },
        { name: '周三', value: '3' },
        { name: '周四', value: '4' },
        { name: '周五', value: '5' },
        { name: '周六', value: '6' },
        { name: '周日', value: '7' }
      ],
      strategyForm: {
        strategyCode: '',
        strategyName: '',
        strategyDesc: '',
        repeatType: '',
        repeatParam: [],
        priority: 0,
        hourList: []
      },
      computeTypeOptions: [
        { name: '不计入', value: 0 },
        { name: '户数均摊', value: 1 },
        { name: '面积均摊', value: 2 }
      ],
      chargingForm: {
        areaCode: '',
        elecUnitPrice: '',
        elecGtComputeType: '',
        elecComputeDesc: '',
        waterUnitPrice: '',
        waterGtComputeType: '',
        waterComputeDesc: '',
        relCoList: []
      },
      zoningList: [],
      ifDisabled: false
    }
  },
  created() {
    this.getAreaList('Area')
    this.getAttrList()
    this.getGwPriceList()
    this.getPvPriceList()
    this.getPriceType()
    this.getStrategyList()
    this.getChargingList()
    this.getRelateShopList()
  },
  methods: {
    formatDict(value, options, key = 'value', name = 'name') {
      let text = ''
      this[options].forEach(item => {
        if (value === item[key]) {
          text = item[name]
        }
      })
      return text
    },
    getGwPriceList() {
      this.loading = true
      listGwPriceConfig(this.queryGwPriceParams).then(response => {
        this.gwPriceList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    gwPriceCancel() {
      this.gwPriceCfgOpen = false
      this.gwPriceReset()
    },
    // 表单重置
    gwPriceReset() {
      this.gwPriceForm = {
        id: null,
        cfgCode: null,
        elecType: null,
        voltageLevel: null,
        degreePrice: null,
        fsPeakDegreePrice: null,
        fsHighDegreePrice: null,
        fsFlatDegreePrice: null,
        fsLowDegreePrice: null,
        maxReqPrice: null,
        transCapacityPrice: null
      }
      this.resetForm('gwPriceForm')
    },
    /** 新增按钮操作 */
    handleGwPriceAdd() {
      this.gwPriceReset()
      this.gwPriceCfgOpen = true
      this.title = '添加电价配置'
    },
    /** 修改按钮操作 */
    handleGwPriceUpdate(row) {
      this.gwPriceReset()
      const id = row.id || this.ids
      getGwPriceConfig(id).then(response => {
        this.gwPriceForm = response.data
        this.gwPriceCfgOpen = true
        this.title = '修改电价配置'
      })
    },
    /** 提交按钮 */
    submitGwPriceForm() {
      this.$refs['gwPriceForm'].validate(valid => {
        if (valid) {
          if (this.gwPriceForm.id != null) {
            updateGwPriceConfig(this.gwPriceForm).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.gwPriceCfgOpen = false
              this.getGwPriceList()
            })
          } else {
            addGwPriceConfig(this.gwPriceForm).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.gwPriceCfgOpen = false
              this.getGwPriceList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleGwPriceDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除电价配置编号为"' + ids + '"的数据项？')
        .then(function() {
          return delGwPriceConfig(ids)
        })
        .then(() => {
          this.getGwPriceList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    /** 查询服务区用电属性列表 */
    getAttrList() {
      this.loading = true
      listAttr(this.queryAttrParams).then(response => {
        this.attrList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    attrCancel() {
      this.attrOpen = false
      this.attrReset()
    },
    // 表单重置
    attrReset() {
      this.attrForm = {
        id: null,
        areaCode: null,
        elecType: null,
        priceCode: null,
        reqCapacityFlag: 0,
        transCapacity: null,
        reqQuantity: null,
        createTime: null,
        updateTime: null
      }
      this.resetForm('attrForm')
    },
    /** 搜索按钮操作 */
    handleAttrQuery() {
      this.queryAttrParams.pageNum = 1
      this.getAttrList()
    },
    handleGwPriceQuery() {
      this.queryGwPriceParams.pageNum = 1
      this.getGwPriceList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.handleAttrQuery()
      this.handleGwPriceQuery()
    },
    /** 新增按钮操作 */
    handleAttrAdd() {
      this.attrReset()
      this.getGwPriceAll()
      this.attrOpen = true
      this.title = '添加服务区用电属性'
    },
    /** 修改按钮操作 */
    handleAttrUpdate(row) {
      this.attrReset()
      this.getGwPriceAll()
      const id = row.id || this.ids
      getAttr(id).then(response => {
        this.attrForm = response.data
        this.attrOpen = true
        this.title = '修改服务区用电属性'
      })
    },
    /** 提交按钮 */
    submitAttrForm() {
      this.$refs['attrForm'].validate(valid => {
        if (valid) {
          if(this.attrList.some(item=>item.areaCode===this.attrForm.areaCode)){
            return this.$modal.msgError('当前园区已存在')
          }
          if (this.attrForm.id != null) {
            updateAttr(this.attrForm).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.attrOpen = false
              this.getAttrList()
            })
          } else {
            addAttr(this.attrForm).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.attrOpen = false
              this.getAttrList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleAttrDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除服务区用电属性编号为"' + ids + '"的数据项？')
        .then(function() {
          return delAttr(ids)
        })
        .then(() => {
          this.getAttrList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    getPvPriceList() {
      this.loading = true
      listPvPriceConfig(this.queryPvPriceParams).then(response => {
        this.pvPriceList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    pvPriceCancel() {
      this.pvPriceOpen = false
      this.pvPriceReset()
    },
    // 表单重置
    pvPriceReset() {
      this.pvPriceForm = {
        id: null,
        cfgCode: null,
        priceName: null,
        objPrice: null,
        stateSubsidy: null,
        localSubsidy: null
      }
      this.resetForm('pvPriceForm')
    },
    /** 新增按钮操作 */
    handlePvPriceAdd() {
      this.pvPriceReset()
      this.pvPriceOpen = true
      this.title = '添加光伏电价配置'
    },
    /** 修改按钮操作 */
    handlePvPriceUpdate(row) {
      this.pvPriceReset()
      const id = row.id || this.ids
      getPvPriceConfig(id).then(response => {
        this.pvPriceForm = response.data
        this.pvPriceOpen = true
        this.title = '修改光伏电价配置'
      })
    },
    /** 提交按钮 */
    submitPvPriceForm() {
      this.$refs['pvPriceForm'].validate(valid => {
        if (valid) {
          if (this.pvPriceForm.id != null) {
            updatePvPriceConfig(this.pvPriceForm).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.pvPriceOpen = false
              this.getPvPriceList()
            })
          } else {
            addPvPriceConfig(this.pvPriceForm).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.pvPriceOpen = false
              this.getPvPriceList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handlePvPriceDelete(row) {
      const ids = row.id || this.ids
      this.$modal
        .confirm('是否确认删除电价配置编号为"' + ids + '"的数据项？')
        .then(function() {
          return delPvPriceConfig(ids)
        })
        .then(() => {
          this.getPvPriceList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    matchReqCapacityFlag(row, column, cellValue, index) {
      const reqCapacityFlagMap = {
        0: '不涉及',
        1: '容量电价',
        2: '需量电价'
      }
      return reqCapacityFlagMap[cellValue] || '未知'
    },
    getPriceType() {
      getElecPriceType().then(response => {
        this.priceTypeOptions = response.data
      })
    },
    // 查询区域列表
    getAreaList(tier) {
      areaTreeSelect(tier).then(response => {
        this.areaOptions = response.data
      })
    },
    getGwPriceAll() {
      listGwPriceConfigAll().then(response => {
        this.gwPriceOptions = response.data
      })
    },
    repeatTypeChange(val) {
      if (val == 5) {
        this.strategyForm.repeatParam = this.weeks.filter(item => item.value < 6).map(item => item.value)
      } else if (val == 6) {
        this.strategyForm.repeatParam = []
      } else {
        this.strategyForm.repeatParam = ''
      }
    },
    /** 查询峰谷电价列表 */
    getStrategyList() {
      const { pageNum, pageSize } = this.strategyParams
      this.strategyParams.loading = true
      listStrategy({ pageNum, pageSize }).then(response => {
        this.strategyList = response.rows
        this.strategyParams.loading = false
      })
    },
    handleStrategyDetail(row) {
      this.ifDisabled = true
      this.resetForm('strategyForm')
      Object.assign(this.strategyForm, row)
      if ([5, 6].includes(this.strategyForm.repeatType)) {
        this.strategyForm.repeatParam = this.strategyForm.repeatParam.split(',')
      }
      this.strategyDialog = true
      this.title = '查看峰谷电价策略'
    },
    handleStrategyAdd() {
      this.ifDisabled = false
      this.resetForm('strategyForm')
      this.strategyForm = this.$options.data().strategyForm
      this.strategyDialog = true
      this.title = '添加峰谷电价策略'
    },
    handleStrategyUpdate(row) {
      this.ifDisabled = false
      this.resetForm('strategyForm')
      Object.assign(this.strategyForm, row)
      if ([5, 6].includes(this.strategyForm.repeatType)) {
        this.strategyForm.repeatParam = this.strategyForm.repeatParam.split(',')
      }
      this.strategyDialog = true
      this.title = '修改峰谷电价策略'
    },
    handleStrategyDelete(row) {
      this.$modal.confirm('是否确认删除').then(() => {
        delStrategy(row.id).then(() => {
          this.getStrategyList()
          this.$modal.msgSuccess('删除成功')
        })
      })
    },
    strategyCancel() {
      this.strategyDialog = false
      this.resetForm('strategyForm')
      this.strategyForm = this.$options.data().strategyForm
    },
    submitStrategyForm() {
      this.$refs['strategyForm'].validate(valid => {
        if (valid) {
          if (this.strategyForm.hourList.length === 0) {
            return this.$modal.msgError(`请添加小时电价数据`)
          }
          let subFlag = false
          let dateFlag = false
          let validIndex = 0
          for (let i = 0; i < this.strategyForm.hourList.length; i++) {
            const item = this.strategyForm.hourList[i]
            if (item.startTime === '' || item.endTime === '' || item.type === '') {
              subFlag = true
              validIndex = i + 1
              break
            }
            if (this.compareTime(item.startTime, item.endTime)) {
              dateFlag = true
              validIndex = i + 1
              break
            }
          }
          if (subFlag) {
            return this.$modal.msgError(`请补全小时电价第${validIndex}行数据`)
          }
          if (dateFlag) {
            return this.$modal.msgError(`小时电价第${validIndex}行开始时刻不能大于结束时刻`)
          }
          if (this.checkTimeRangesOverlap()) {
            return this.$modal.msgError(`小时电价存在时刻交叉，请调整`)
          }
          // 特殊处理
          if ([5, 6].includes(this.strategyForm.repeatType)) {
            this.strategyForm.repeatParam = this.strategyForm.repeatParam.join()
          }
          this.strategyForm.hourList.forEach(item => {
            item.strategyCode = this.strategyForm.strategyCode
          })
          if (this.strategyForm.id) {
            updateStrategy(this.strategyForm).then(() => {
              this.$modal.msgSuccess('修改成功')
              this.strategyDialog = false
              this.getStrategyList()
            })
          } else {
            addStrategy(this.strategyForm).then(() => {
              this.$modal.msgSuccess('新增成功')
              this.strategyDialog = false
              this.getStrategyList()
            })
          }
        }
      })
    },
    compareTime(t1, t2) {
      const d = new Date()
      const ft1 = d.setHours(t1.split(':')[0], t1.split(':')[1], t1.split(':')[2])
      const ft2 = d.setHours(t2.split(':')[0], t2.split(':')[1], t2.split(':')[2])
      return ft1 > ft2
    },
    checkTimeRangesOverlap() {
      const ranges = this.strategyForm.hourList.map(item => {
        const d = new Date()
        const ft1 = d.setHours(item.startTime.split(':')[0], item.startTime.split(':')[1], item.startTime.split(':')[2])
        const ft2 = d.setHours(item.endTime.split(':')[0], item.endTime.split(':')[1], item.endTime.split(':')[2])
        return [ft1, ft2]
      })
      // 将时间段按照开始时间排序
      const sortedRanges = ranges.slice().sort((a, b) => a[0] - b[0])
      // 检查时间段是否重叠
      for (let i = 1; i < sortedRanges.length; i++) {
        if (sortedRanges[i][0] < sortedRanges[i - 1][1]) {
          return true
        }
      }
      // 所有时间段都没有重叠
      return false
    },
    addSub() {
      this.strategyForm.hourList.push({
        startTime: '',
        endTime: '',
        type: ''
      })
    },
    deleteSub(index) {
      this.strategyForm.hourList.splice(index, 1)
    },
    /** 查询商户计费列表 */
    getChargingList() {
      const { pageNum, pageSize } = this.chargingParams
      this.chargingParams.loading = true
      listCharging({ pageNum, pageSize }).then(response => {
        this.chargingList = response.rows
        this.chargingParams.loading = false
      })
    },
    getRelateShopList(areaCode) {
      listZoning({
        areaCode,
        tagCodeList: ['Area_01']
      }).then(({ rows }) => {
        this.zoningList = rows
      })
    },
    handleChargingAdd() {
      this.resetForm('chargingForm')
      this.chargingForm = this.$options.data().chargingForm
      this.chargingDialog = true
      this.title = '添加商户计费配置'
    },
    handleChargingUpdate(row) {
      this.resetForm('chargingForm')
      Object.assign(this.chargingForm, row)
      this.chargingForm.relCoList = this.chargingForm.relCoList.map(item => item.zoningCode)
      this.getRelateShopList(this.chargingForm.areaCode)
      this.chargingDialog = true
      this.title = '修改商户计费配置'
    },
    handleChargingDelete(row) {
      this.$modal.confirm('是否确认删除').then(() => {
        delCharging(row.id).then(() => {
          this.getChargingList()
          this.$modal.msgSuccess('删除成功')
        })
      })
    },
    chargingCancel() {
      this.chargingDialog = false
      this.resetForm('chargingForm')
      this.chargingForm = this.$options.data().chargingForm
    },
    submitChargingForm() {
      this.$refs['chargingForm'].validate(valid => {
        if (valid) {
          this.chargingForm.relCoList = this.chargingForm.relCoList.map(item => ({ priceCfgId: this.chargingForm.id, zoningCode: item }))
          if (this.chargingForm.id) {
            updateCharging(this.chargingForm).then(() => {
              this.$modal.msgSuccess('修改成功')
              this.chargingDialog = false
              this.getChargingList()
            })
          } else {
            addCharging(this.chargingForm).then(() => {
              this.$modal.msgSuccess('新增成功')
              this.chargingDialog = false
              this.getChargingList()
            })
          }
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  ::v-deep .el-tabs__content {
    overflow: initial;
  }
}
.sub-table {
  .el-icon-delete {
    cursor: pointer;
  }
  .operateBtns {
    cursor: pointer;
    i {
      color: #1990ff;
      margin-left: 5px;
    }
  }
  ::v-deep .el-date-editor {
    width: 100% !important;
  }
}
.custom-checkbox-group {
  max-height: 120px;
  overflow-y: auto;
}
.strategyForm {
  ::v-deep .el-input.is-disabled .el-input__inner {
    color: #606266;
    background: #fff;
  }
}
</style>
<style lang="scss">
.custom-dialog {
  .el-dialog__body {
    padding-bottom: 0;
  }
}
</style>
