<template>
   <a-spin :spinning="confirmLoading">
     <j-form-container :disabled="formDisabled">
       <!-- 主表单区域 -->
       <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
         <div class="cmms-dialog-item-title">基本信息</div>
         <a-row>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="名称" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="name">
              <a-input v-model="model.name" placeholder="请输入名称" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="能源分类" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="energytypeid">
              <j-search-select-tag v-model="model.energytypeid" placeholder="请选择设备" dict="base_energy_type,name,id"  />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item :labelCol="labelCol" :wrapperCol="wrapperCol" prop="ratetype">
              <span slot="label">
                费率类型&nbsp;
                <a-tooltip title="切换类型后，价格信息表将重置">
                  <a-icon type="exclamation-circle" />
                </a-tooltip>
              </span>
              <j-dict-select-tag type="list" v-model="model.ratetype" dictCode="energy_rate_type" placeholder="请选择费率类型" @change="handleChangeType" :disabled="ratetypeDisabled"/>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="rateunit">
              <a-input v-model="model.rateunit" placeholder="请输入单位" ></a-input>
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="费率有效期开始" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="begintime">
              <j-date placeholder="请选择费率有效期开始" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" v-model="model.begintime" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="12">
            <a-form-model-item label="费率有效期结束" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="endtime">
              <j-date placeholder="请选择费率有效期结束" :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" v-model="model.endtime" style="width: 100%" />
            </a-form-model-item>
          </a-col>
          <a-col :xs="24" :sm="24">
            <a-form-model-item label="备注" :labelCol="labelCol2" :wrapperCol="wrapperCol2" prop="remark">
              <a-textarea v-model="model.remark" placeholder="请输入备注" rows="3" ></a-textarea>
            </a-form-model-item>
          </a-col>
        </a-row>
      <!-- </a-form-model>
     </j-form-container> -->
      <!-- 子表单区域 -->
      <div class="cmms-dialog-item-title">价格信息表详情</div>
      <a-button type="primary" style="margin-bottom:10px;" @click="newMember">新增</a-button>
      <a-table
        size="small"
        :columns="model.columns1"
        :dataSource="model.data"
        :pagination="false"
        :rowKey="(record, index) => { return index }"
        bordered
        class="j-table-force-nowrap"
        >

        <template slot="begintime" slot-scope="text, record,index">
            <a-form-model-item :prop="'data.'+index+'.begintime'" :rules="validatorRules.begintime2" style="margin-bottom: 0px;">
              <a-time-picker value-format="HH:mm:ss" placeholder="请选择分时开始时间" v-model="record.begintime" style="width: 100%" />
            </a-form-model-item>
        </template>
        <template slot="endtime" slot-scope="text, record,index">
            <a-form-model-item :prop="'data.'+index+'.endtime'" :rules="validatorRules.endtime2" style="margin-bottom: 0px;">
              <a-time-picker value-format="HH:mm:ss" placeholder="请选择分时结束时间" v-model="record.endtime" style="width: 100%" />
            </a-form-model-item>
        </template>
        <template slot="pandv" slot-scope="text, record,index">
            <a-form-model-item :prop="'data.'+index+'.pandv'" :rules="validatorRules.pandv" style="margin-bottom: 0px;">
              <!-- <j-dict-select-tag type="list" v-model="record.pandv" dictCode="ems_pandv" placeholder="请选择峰平谷" style="width: 100%" /> -->
              <a-select
              v-model="record.pandv"
              placeholder="请选择峰平谷"
              showSearch
              :filterOption="filterOption"
              :options="typeOptions">
              </a-select>
            </a-form-model-item>
        </template>
        <template slot="price" slot-scope="text, record,index">
            <a-form-model-item :prop="'data.'+index+'.price'" :rules="validatorRules.price" style="margin-bottom: 0px;">
              <a-input v-model="record.price" placeholder="请输入价格" ></a-input>
            </a-form-model-item>
        </template>
        <template slot="beginamount" slot-scope="text, record,index">
            <a-form-model-item :prop="'data.'+index+'.beginamount'" :rules="validatorRules.beginamount" style="margin-bottom: 0px;">
              <a-input v-model="record.beginamount" placeholder="请输入起始量" ></a-input>
            </a-form-model-item>
        </template>
        <template slot="endamount" slot-scope="text, record,index">
            <a-form-model-item :prop="'data.'+index+'.endamount'" :rules="validatorRules.endamount" style="margin-bottom: 0px;">
              <a-input v-model="record.endamount" placeholder="请输入结束量" ></a-input>
            </a-form-model-item>
        </template>
        <template slot="operation" slot-scope="text, record, index">
          <span>
            <a-popconfirm title="是否要删除此行？" @confirm="remove(record, index)">
                <a>删除</a>
            </a-popconfirm>
          </span>
        </template>
      </a-table>
      </a-form-model>
    </j-form-container>
      <!-- <a-tabs v-model="activeKey" @change="handleChangeTabs">
        <a-tab-pane tab="详情" :key="refKeys[0]" :forceRender="true">
          <j-editable-table
            :ref="refKeys[0]"
            :loading="model.loading"
            :columns="model.columns"
            :dataSource="model.data"
            :maxHeight="300"
            :disabled="formDisabled"
            :rowNumber="true"
            :rowSelection="true"
            :actionButton="true"/>
        </a-tab-pane>
      </a-tabs> -->
    </a-spin>
</template>

<script>

  import { FormTypes,getRefPromise,VALIDATE_NO_PASSED } from '@/utils/JEditableTableUtil'
  import { JEditableTableModelMixin } from '@/mixins/JEditableTableModelMixin'
  import { validateDuplicateValue } from '@/utils/util'
  import {ajaxGetDictItems,getDictItemsFromCache} from '@/api/api'
  import { httpAction, getAction } from '@/api/manage'

  export default {
    name: 'EnergyRateForm',
    mixins: [JEditableTableModelMixin],
    components: {
    },
    data() {
      return {
        // typeOptions: [
        //   {label: '尖', value: 0},
        //   {label: '峰', value: 1},
        //   {label: '平', value: 2},
        //   {label: '谷', value: 3},
        // ],
        labelCol: {
          xs: { span: 24 },
          sm: { span: 6 },
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 16 },
        },
        labelCol2: {
          xs: { span: 24 },
          sm: { span: 3 },
        },
        wrapperCol2: {
          xs: { span: 24 },
          sm: { span: 20 },
        },
        model:{
          loading: false,
          data: [],
          baseEnergyRateDetailList: [],
          columns1: []
        },
        validatorRules: {
           energyrateid: [
              { required: true, message: '请输入能源费率ID!'},
           ],
           name: [
              { required: true, message: '请输入名称!'},
           ],
           energytypeid: [
              { required: true, message: '请输入能源分类ID!'},
           ],
           ratetype: [
              { required: true, message: '请输入费率类型：分时费率、阶梯费率!'},
           ],
          //  rateunit: [
          //     { required: true, message: '请输入单位!'},
          //  ],
            begintime: [
              { required: true, message: '请输入费率有效期开始!'},
            ],
            endtime: [
              { required: true, message: '请输入费率有效期结束!'},
            ],
            begintime2: [
              { required: true, message: '请选择分时开始时间!'},
            ],
            endtime2: [
              { required: true, message: '请选择分时结束时间!'},
            ],
            pandv: [
              { required: true, message: '请选择峰平谷!'},
            ],
            price: [
              { required: true, message: '请输入价格!'},
            ],
            beginamount: [
              { required: true, message: '请输入起始量!'},
            ],
            endamount: [
              { required: true, message: '请输入结束量!'},
            ],
        },
        // validatorListRules: {
        //   begintime: [
        //     { required: true, message: '请选择分时开始时间!'},
        //   ],
        //   endtime: [
        //     { required: true, message: '请选择分时结束时间!'},
        //   ],
        //   pandv: [
        //     { required: true, message: '请选择峰平谷!'},
        //   ],
        //   price: [
        //     { required: true, message: '请输入价格!'},
        //   ],
        //   beginamount: [
        //     { required: true, message: '请输入起始量!'},
        //   ],
        //   endamount: [
        //     { required: true, message: '请输入结束量!'},
        //   ],
        // },
        // 新增时子表默认添加几行空数据
        addDefaultRowNum: 1,
        refKeys: ['baseEnergyRateDetail', ],
        tableKeys:['baseEnergyRateDetail', ],
        activeKey: 'baseEnergyRateDetail',
        // base_energy_rate_detail
        // baseEnergyRateDetailTable: {
        //   loading: false,
        //   data: [],
        //   columns1: []
        // },
        url: {
          add: "/energyRate/energyRate/add",
          edit: "/energyRate/energyRate/edit",
          baseEnergyRateDetail: {
            list: '/energyRate/energyRate/queryDetailByMainId',
            list2: '/energyRate/energyRate/xqqueryById'
          },
        },
        count: 1,
        ratetype: '',
        ratetypeDisabled: false,
        dictCode: 'ems_pandv'
      }
    },
    props: {
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      }
    },
    computed: {
      formDisabled(){
        return this.disabled
      },
    },
    created () {
      this.initDictData()
    },
    methods: {
      initDictData() {
        //优先从缓存中读取字典配置
        if(getDictItemsFromCache(this.dictCode)){
          this.typeOptions = getDictItemsFromCache(this.dictCode);
          return
        }

        //根据字典Code, 初始化字典数组
        ajaxGetDictItems(this.dictCode, null).then((res) => {
          if (res.success) {
            this.typeOptions = res.result;
          }
        })
      },
      filterOption (value, option) {
          return option.componentOptions.children[0].text.indexOf(value) >= 0
      },
      addBefore(){
            this.model.data=[]
      },
      getAllTable() {
        let values = this.tableKeys.map(key => getRefPromise(this, key))
        return Promise.all(values)
      },
      // 新增
      add(){
        // this.model = {}
        this.visible = true;
      },
      // 修改
      edit (record) {
        this.ratetypeDisabled = true
        getAction(this.url.baseEnergyRateDetail.list2, {id:record.id}).then((res) => {
          console.log(77777,res)
          this.model = res.result
          this.model.data = this.model.baseEnergyRateDetailList
          if (this.model.ratetype == 1) {
            this.model.columns1 = [
              {
                title: '分时开始时间',
                dataIndex: 'begintime',
                key: 'begintime',
                width:"200px",
                align: 'center',
                scopedSlots: { customRender: 'begintime' },
              },
              {
                title: '分时结束时间',
                dataIndex: 'endtime',
                key: 'endtime',
                width:"200px",
                align: 'center',
                scopedSlots: { customRender: 'endtime' },
              },
              {
                title: '峰平谷',
                dataIndex: 'pandv',
                key: 'pandv',
                width:"200px",
                align: 'center',
                scopedSlots: { customRender: 'pandv' },
              },
              {
                title: '价格',
                dataIndex: 'price',
                key: 'price',
                width:"200px",
                align: 'center',
                scopedSlots: { customRender: 'price' },
              },
              {
                title: '操作',
                key: 'operation',
                align: 'center',
                width:"100px",
                scopedSlots: { customRender: 'operation' }
              }
            ]
          } else {
            this.model.columns1 = [
              {
                title: '起始量',
                dataIndex: 'beginamount',
                key: 'beginamount',
                width:"200px",
                align: 'center',
                scopedSlots: { customRender: 'beginamount' },
              },
              {
                title: '结束量',
                dataIndex: 'endamount',
                key: 'endamount',
                width:"200px",
                align: 'center',
                scopedSlots: { customRender: 'endamount' },
              },
              {
                title: '价格',
                dataIndex: 'price',
                key: 'price',
                width:"200px",
                align: 'center',
                scopedSlots: { customRender: 'price' },
              },
              {
                title: '操作',
                key: 'operation',
                align: 'center',
                width:"100px",
                scopedSlots: { customRender: 'operation' }
              }
            ]
          }
        })
        // this.model = Object.assign({}, record);
        this.visible = true;
      },
      /** 调用完edit()方法之后会自动调用此方法 */
      editAfter() {
        this.$nextTick(() => {
        })
        // 加载子表数据
        if (this.model.id) {
          let params = { id: this.model.id }
          this.requestSubTableData(this.url.baseEnergyRateDetail.list, params, this.model)
        }
      },
      //校验所有一对一子表表单
      validateSubForm(allValues){
        return new Promise((resolve,reject)=>{
          Promise.all([
          ]).then(() => {
            resolve(allValues)
          }).catch(e => {
            if (e.error === VALIDATE_NO_PASSED) {
              // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
              this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
            } else {
              console.error(e)
            }
          })
        })
      },
      /** 整理成formData */
      classifyIntoFormData(allValues) {
        let main = Object.assign(this.model, allValues.formValue)

        return {
          ...main, // 展开
          baseEnergyRateDetailList: allValues.tablesValue[0].values,
        }
      },
      validateError(msg){
        this.$message.error(msg)
      },
      close() {
        this.visible = false
        this.$emit('close')
        this.$refs.form.clearValidate();
      },
      // 获取选中的费率类型
      handleChangeType(value){
        console.log(99,value)
        if (value == '') {
          // this.model.columns1 = []
          this.model.data = []
          this.count = 1
          this.ratetype = ''
        }
        if (value != this.ratetype) {
          this.model.data = []
          this.count = 1
        }
        if (value == 1) {
          this.ratetype = value
          this.model.columns1 = [
            {
              title: '分时开始时间',
              dataIndex: 'begintime',
              key: 'begintime',
              width:"200px",
              align: 'center',
              scopedSlots: { customRender: 'begintime' },
            },
            {
              title: '分时结束时间',
              dataIndex: 'endtime',
              key: 'endtime',
              width:"200px",
              align: 'center',
              scopedSlots: { customRender: 'endtime' },
            },
            {
              title: '峰平谷',
              dataIndex: 'pandv',
              key: 'pandv',
              width:"200px",
              align: 'center',
              scopedSlots: { customRender: 'pandv' },
            },
            {
              title: '价格',
              dataIndex: 'price',
              key: 'price',
              width:"200px",
              align: 'center',
              scopedSlots: { customRender: 'price' },
            },
            {
              title: '操作',
              key: 'operation',
              align: 'center',
              width:"100px",
              scopedSlots: { customRender: 'operation' }
            }
          ]
          this.model.data.push({
            key: this.count + '',
            begintime: '',
            endtime: '',
            pandv: '',
            price: '',
            beginamount: '',
            endamount: ''
          })
          this.count++
          console.log(this.model.data)
        } 
        if (value == 2) {
          this.ratetype = value
          this.model.columns1 = [
            {
              title: '起始量',
              dataIndex: 'beginamount',
              key: 'beginamount',
              width:"200px",
              align: 'center',
              scopedSlots: { customRender: 'beginamount' },
            },
            {
              title: '结束量',
              dataIndex: 'endamount',
              key: 'endamount',
              width:"200px",
              align: 'center',
              scopedSlots: { customRender: 'endamount' },
            },
            {
              title: '价格',
              dataIndex: 'price',
              key: 'price',
              width:"200px",
              align: 'center',
              scopedSlots: { customRender: 'price' },
            },
            {
              title: '操作',
              key: 'operation',
              align: 'center',
              width:"100px",
              scopedSlots: { customRender: 'operation' }
            }
          ]
          this.model.data.push({
            key: this.count + '',
            begintime: '',
            endtime: '',
            pandv: '',
            price: '',
            beginamount: '',
            endamount: ''
          })
          this.count++
          console.log(this.model.data)
        }
      },
      // 创建一条新数据
      newMember() {
        console.log(this.model.ratetype)
        if (this.model.ratetype == undefined) {
          this.$message.warning('请先选择费率类型');
        } else {
          this.model.data.push({
            key: this.count + '',
            begintime: '',
            endtime: '',
            pandv: '',
            price: '',
            beginamount: '',
            endamount: ''
          })
          this.count++
          console.log(this.model.data)
        }
      },
      remove(record, index) {
        this.model.data.splice(index, 1)
        // if (record.id) {
        //   const key = record.id
        //   const newData = this.model.data.filter(item => item.id !== key)
        //   this.model.data = newData
        //   console.log(this.model.data)
        // } else {
        //   const key = record.key
        //   const newData = this.model.data.filter(item => item.key !== key)
        //   this.model.data = newData
        // }
        // console.log(key)
        // const newData = this.model.data.filter(item => item.key !== key)
        // this.model.data = newData
      },
      submitForm () {
        const that = this;
        // 触发表单验证
        this.$refs.form.validate(valid => {
          if (valid) {
            that.model.baseEnergyRateDetailList = that.model.data
            that.confirmLoading = true;
            let httpurl = '';
            let method = '';
            if(!this.model.id){
              httpurl+=this.url.add;
              method = 'post';
            }else{
              httpurl+=this.url.edit;
               method = 'put';
            }
            httpAction(httpurl,this.model,method).then((res)=>{
              if(res.success){
                that.$message.success(res.message);
                that.$emit('ok');
              }else{
                that.$message.warning(res.message);
              }
            }).finally(() => {
              that.confirmLoading = false;
            })
          }
        })
      },
    }
  }
</script>

<style scoped>
@import "~@/assets/less/uStyle.less";
</style>