<!--
  Description: 配电网支线参数新增或修改
  Author: 李亚光
  Date: 2023-04-21
 -->
<script lang="ts" setup name="deviceAdd">
import type { FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { electricityBranchAdd, electricityBranchDel, electricityBranchUpdate, electricityNode } from '@/api/api/index'
import { getDictByCode } from '@/api/system/dict'
const props = defineProps({
  id: {
    type: String,
    required: true,
  },
})
const emits = defineEmits(['refresh'])
const dataFormRef = ref()
const dialogFormVisible = ref(false) // 对话框是否显示
const dialogStatus = ref('') // 对话框类型：create,update
const isEditMode = ref(true)
const areaForm = ref({
  b: '', // 支路电纳标幺值
  branchNumber: '', // 支路编号
  electricityId: '', // 所属电网主键
  fbusId: '', // 支路首段节点ID
  r: '', // 支路电阻标幺值
  ratea: '', // 长距离输电容量
  rateb: '', // 短距离输电容量
  ratec: '', // 紧急距离输电容量
  tbusId: '', // 支路末端节点ID
  x: '', // 支路电抗标幺值
  angle: '', // 角度
  angmax: '', // 支路最大相位角
  angmin: '', // 支路最小相位角
  ratio: '', // 支路变比
  status2: '', // 状态
}) // 表单
const textMap: { [key: string]: string } = {
  update: '编辑',
  create: '新增',
  detail: '详情',
} // 表头显示标题
const btnLoading = ref(false) // 保存按钮的加载中状态
const rules: FormRules = {
  b: [{ required: true, message: '请输入支路电纳标幺值', trigger: ['blur', 'change'] }],
  branchNumber: [{ required: true, message: '请输入支路编号', trigger: ['blur', 'change'] }],
  fbusId: [{ required: true, message: '请选择支路首端节点', trigger: ['blur', 'change'] }],
  tbusId: [{ required: true, message: '请选择支路末端节点', trigger: ['blur', 'change'] }],
  r: [{ required: true, message: '请输入支路电阻标幺值', trigger: ['blur', 'change'] }],
  ratea: [{ required: true, message: '请输入长距离输电容量', trigger: ['blur', 'change'] }],
  rateb: [{ required: true, message: '请输入长距离输电容量', trigger: ['blur', 'change'] }],
  ratec: [{ required: true, message: '请输入紧急距离输电容量', trigger: ['blur', 'change'] }],
  x: [{ required: true, message: '请输入支路电抗标幺值', trigger: ['blur', 'change'] }],
  angle: [{ required: true, message: '请输入支路相位角', trigger: ['blur', 'change'] }],
  angmax: [{ required: true, message: '请输入支路最大相位角', trigger: ['blur', 'change'] }],
  angmin: [{ required: true, message: '请输入支路最小相位角', trigger: ['blur', 'change'] }],
  ratio: [{ required: true, message: '请输入支路变比', trigger: ['blur', 'change'] }],
  status2: [{ required: true, message: '请选择支路状态', trigger: ['blur', 'change'] }],
} // 前端校验规则
// 获取节点列表
const nodeList = ref<any[]>([])
const fetchNodeList = (id: string) => {
  electricityNode(id).then((res) => {
    nodeList.value = res.data.map(item => ({ ...item, busId: item.busId.toString() }))
  })
}
// 获取节点状态
const statusList = ref<any[]>([])
const fetcStatusList = () => {
  getDictByCode('branch_node_status').then((res) => {
    statusList.value = res.data
  })
}
fetcStatusList()
// 重置表单
const resetForm = () => {
  areaForm.value = {
    b: '', // 支路电纳标幺值
    branchNumber: '', // 支路编号
    electricityId: '', // 所属电网主键
    fbusId: '', // 支路首段节点ID
    r: '', // 支路电阻标幺值
    ratea: '', // 长距离输电容量
    rateb: '', // 短距离输电容量
    ratec: '', // 紧急距离输电容量
    tbusId: '', // 支路末端节点ID
    x: '', // 支路电抗标幺值
    angle: '', // 角度
    angmax: '', // 支路最大相位角
    angmin: '', // 支路最小相位角
    ratio: '', // 支路变比
    status2: '', // 状态
  }
}
// 初始化对话框
const initDialog = (dialogStatusValue: string, row: any, id: string) => {
  fetchNodeList(id)
  dialogStatus.value = dialogStatusValue
  dialogFormVisible.value = true
  btnLoading.value = false
  if (dialogStatus.value === 'create') { // 如果是新增，清除验证
    resetForm()
    isEditMode.value = false
    nextTick(() => {
      dataFormRef.value.clearValidate()
    })
    areaForm.value.electricityId = id
  }
  else if (dialogStatus.value === 'update' || dialogStatus.value === 'detail') { // 如果是修改，将row中数据填写到输入框中
    areaForm.value = row
    areaForm.value.status2 = areaForm.value.status2.toString()
    isEditMode.value = true
  }
  if (dialogStatus.value === 'detail') {
    isEditMode.value = false
  }
}
defineExpose({
  initDialog,
})

// 新增数据
const createData = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      btnLoading.value = true
      electricityBranchAdd(areaForm.value).then((response) => {
        if (response.code === 200) {
          btnLoading.value = false
          // 通知父组件刷新状态
          setTimeout(() => {
            emits('refresh')
          })
          ElMessage({
            message: '添加成功',
            type: 'success',
          })
          dialogFormVisible.value = false
        }
      }).catch((_) => { // 异常情况，loading置为false
        btnLoading.value = false
      })
    }
  })
}

// 修改数据
const updateData = () => {
  dataFormRef.value.validate((valid: any) => {
    if (valid) {
      btnLoading.value = true
      electricityBranchUpdate(areaForm.value).then((response) => {
        if (response.code === 200) {
          ElMessage({
            message: '修改成功',
            type: 'success',
          })
          dataFormRef.value.clearValidate()
          setTimeout(() => {
            emits('refresh')
          })
          dialogFormVisible.value = false
        }
      }).catch((_) => { // 异常情况，loading置为false
        btnLoading.value = false
      })
    }
  })
}

// 保存数据
const saveData = () => {
  if (dialogStatus.value === 'update') {
    updateData()
  }
  else if (dialogStatus.value === 'create') {
    createData()
  }
}
const cancel = () => {
  dialogFormVisible.value = false
}
</script>

<template>
  <el-dialog v-model="dialogFormVisible" :title="textMap[dialogStatus]" append-to-body>
    <el-form ref="dataFormRef" :class="[dialogStatus === 'detail' ? 'isDetail' : '']" :rules="rules" :model="areaForm" label-position="right" label-width="160px" :disabled="!isEditMode">
      <el-row :gutter="24">
        <el-col :span="24">
          <el-form-item label="支路编号:" prop="branchNumber">
            <el-input v-model="areaForm.branchNumber" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="支路首端节点:" prop="fbusId">
            <el-select
              v-model="areaForm.fbusId" class="m-2"
              style="width: 100%;"
            >
              <el-option v-for="item in nodeList" :key="item.busId" :label="item.nodeName" :value="item.busId" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支路末端节点:" prop="tbusId">
            <!-- <el-input v-model="areaForm.tbusId" :placeholder="dialogStatus === 'create' ? '请输入支路末端节点' : ''" /> -->
            <el-select
              v-model="areaForm.tbusId" class="m-2"
              style="width: 100%;"
            >
              <el-option v-for="item in nodeList" :key="item.busId" :label="item.nodeName" :value="item.busId" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="支路电阻标幺值:" prop="r">
            <el-input v-model="areaForm.r" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支路电纳标幺值:" prop="b">
            <el-input v-model="areaForm.b" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="长距离输电容量:" prop="ratea">
            <el-input v-model="areaForm.ratea" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="短距离输电容量:" prop="rateb">
            <el-input v-model="areaForm.rateb" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="紧急距离输电容量:" prop="ratec">
            <el-input v-model="areaForm.ratec" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支路变比:" prop="ratio">
            <el-input v-model="areaForm.ratio" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="支路相位角:" prop="angle">
            <el-input v-model="areaForm.angle" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支路最小相位角:" prop="angmin">
            <el-input v-model="areaForm.angmin" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="24">
        <el-col :span="12">
          <el-form-item label="支路最大相位角:" prop="angmax">
            <el-input v-model="areaForm.angmax" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="支路是否运行:" prop="status2">
            <el-select
              v-model="areaForm.status2" class="m-2"
              style="width: 100%;"
            >
              <el-option v-for="item in statusList" :key="item.id" :label="item.name" :value="item.value" />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button :loading="btnLoading" type="primary" @click="saveData">
          保存
        </el-button>
        <el-button @click="cancel">
          取消
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.el-dialog {
  width: 700px;
}

.el-select {
  width: 100%;
}

.isDetail {
  ::v-deep {
    .el-form-item.is-required:not(.is-no-asterisk) .el-form-item__label-wrap > .el-form-item__label::before,
    .el-form-item.is-required:not(.is-no-asterisk) > .el-form-item__label::before {
      display: none;
    }
  }
}
</style>
