<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="参数模版编号" prop="paramClassId">
        <el-input v-model="queryParams.paramClassId" placeholder="请输入参数模版编号" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item label="参数模板名称" prop="paramClassName">
        <el-input v-model="queryParams.paramClassName" placeholder="请输入参数模板名称" clearable @keyup.enter="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button type="info" plain icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="success" icon="Plus" @click="handleAdd">新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="success" icon="Edit" @click="handleUpdate">修改</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <el-button type="success" icon="Delete" @click="handleDelete">删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button type="warning" icon="Download" @click="handleExport">导出</el-button>
      </el-col> -->
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="heatParamModelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <!-- <el-table-column label="主键" align="center" prop="id" /> -->
      <el-table-column label="热源" align="center" prop="standardConfId">
        <template #default="scope">
          {{ getHeatName(scope.row.standardConfId) }}
        </template>
      </el-table-column>
      <el-table-column label="参数模版" align="center" prop="paramClassId">
        <template #default="scope">
          {{ getParamClassName(scope.row.paramClassId) }}
        </template>
      </el-table-column>
      <el-table-column label="是否启用计算" align="center" prop="computeSwitch">
        <template #default="scope">
          <el-switch v-model="scope.row.computeSwitch" @change="changeSwitch(scope.row)"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <!-- <el-button type="text" icon="Edit" @click="handleUpdate(scope.row)">修改</el-button> -->
          <el-button type="text" icon="Delete" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改热源推送参数配置对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="heatParamModelRef" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="参数模版编号" prop="paramClassId">
              <el-select v-model="form.paramClassId" filterable placeholder="请选择参数模版ID" @change="paramClassChange"
                multiple>
                <el-option v-for="dict in paramClassListNew" :label="dict.paramClassName" :value=dict.paramClassCode>
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<style lang="scss" > @import "@/assets/styles/self-defined.scss";

 .center-message {
   position: fixed;
   left: 50%;
   top: 50%;
   transform: translate(-50%, -50%);
 }
</style>
<script setup name="HeatParamModel">
import { listHeatParamModel, getHeatParamModel, delHeatParamModel, addHeatParamModel, updateHeatParamModel, addBatchHeatParamModel, updateHeatParamModelNew, listHeatParamModelNoPage } from "@/api/model/heatparammodel";
import { listNoPage } from "@/api/model/heatapiconf";
import { listParamclassNoPage } from "@/api/model/paramclass";
import { ElMessageBox } from 'element-plus';
const { proxy } = getCurrentInstance();

const heatParamModelList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const router = useRouter();
const heatList = ref([]);
const standardConfId = (router.currentRoute._value.query.standardConfId !== undefined && router.currentRoute._value.query.standardConfId !== null && router.currentRoute._value.query.standardConfId !== "") ? router.currentRoute._value.query.standardConfId : null;
const paramClassList = ref([]);
const paramClassSelectedOld = ref([]);
const paramClassListNew = ref([]);
const data = reactive({
  form: {
    standardConfId: standardConfId,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    standardConfId: null,
    paramClassId: null,
    paramClassName: null
  },
  rules: {
  }
});

const { queryParams, form, rules } = toRefs(data);
/** 查询热源推送参数配置列表 */

function getList() {
  if (standardConfId != null && standardConfId != undefined && standardConfId != "") {
    queryParams.value.standardConfId = standardConfId;
  }
  loading.value = true;
  listHeatParamModel(queryParams.value).then(response => {
    heatParamModelList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    tentantId: null,
    version: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    deptId: null,
    userId: null,
    deleteBy: null,
    deleteTime: null,
    id: null,
    standardConfId: standardConfId,
    paramClassId: null,
    paramClassName: null
  };
  proxy.resetForm("heatParamModelRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  paramClassSelectedOld.value = [];
  let param = {
    standardConfId:standardConfId
  }
  listHeatParamModelNoPage(param).then(response => {
    response.data?.forEach(item=>{
      paramClassSelectedOld.value.push(item.paramClassId);
    });
    paramClassListNew.value = paramClassList.value.filter(item => {
      return !paramClassSelectedOld.value.includes(item.paramClassCode); 
    }); 
  });
  open.value = true;
  title.value = "添加热源推送参数配置";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  paramClassSelectedOld.value = [];
  paramClassListNew.value = paramClassList.value;
  let param = {
    standardConfId:standardConfId
  }
  listHeatParamModelNoPage(param).then(response => {
    response.data?.forEach(item=>{
      paramClassSelectedOld.value.push(item.paramClassId);
    });
    form.value.paramClassId = paramClassSelectedOld.value;
    open.value = true;
    title.value = "修改热源推送参数配置";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["heatParamModelRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        let paramSub = new Array();
        form.value.paramClassId?.forEach(item => {
          paramSub.push({
            paramClassId: item,
            standardConfId: standardConfId,
            computeSwitch: true,
          })
        })
        let paramAll = {
          standardConfId: standardConfId,
          dcHeatParamModelList: paramSub
        }
        updateHeatParamModelNew(paramAll).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        let paramSub = new Array();
        form.value.paramClassId?.forEach(item => {
          paramSub.push({
            paramClassId: item,
            standardConfId: standardConfId,
            computeSwitch: true,
          })
        })
        addBatchHeatParamModel(paramSub).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除热源推送参数配置编号为"' + _ids + '"的数据项？').then(function () {
    return delHeatParamModel(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => { });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('model/heatParamModel/export', {
    ...queryParams.value
  }, `heatParamModel_${new Date().getTime()}.xlsx`)
}

function getParamModel() {
  listParamclassNoPage({}).then(response => {
    paramClassList.value = response.data;
  });
}

function getParamClassName(paramClassId) {
  for (let item of paramClassList.value) {
    if (item.paramClassCode === paramClassId) {
      return item.paramClassName
    }
  }
  return ''
}


function getHeatList() {
  listNoPage({}).then(response => {
    heatList.value = response.data;
  });
}


function getHeatName(standardConfId) {
  for (let item of heatList.value) {
    if (String(item.id) === standardConfId) {
      return item.orgName
    }
  }
  return ''
}

// created() {
//   eventBus.$on('reload-heatParamModel', () => {
//     this.reload(); 
//   });
// }


function changeSwitch(row){
  ElMessageBox.confirm('确定修改该计算启用状态吗', '提示', {
      distinguishCancelAndClose: true,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
  })
  .then(() => {
    console.log("确定");
    let param = {
      id:row.id,
      computeSwitch:row.computeSwitch
    }
    updateHeatParamModel(param).then(response=>{
      theSameToEachOther(row);
    });
    //同步供温和回温开关
    
  })
  .catch((action) => {
    console.log("取消");
    row.computeSwitch = !row.computeSwitch;
  })
  
}

function theSameToEachOther(row){
  if(row.paramClassId == '045'){
    heatParamModelList.value.forEach(item=>{
      if(item.paramClassId == '046'){
        let param = {
          id: item.id,
          computeSwitch:row.computeSwitch,
        }
        updateHeatParamModel(param).then(response=>{
          getList();
        });
      }
    })
  }else if(row.paramClassId == '046'){
    heatParamModelList.value.forEach(item=>{
      if(item.paramClassId == '045'){
        let param = {
          id: item.id,
          computeSwitch:row.computeSwitch,
        }
        updateHeatParamModel(param).then(response=>{
          getList();
        });
      }
    })
  }
}



getHeatList();
getParamModel();
getList();
</script>
