<template>
  <div class="app-container">
    <div class="submitBtn">
      <el-button
        type="primary"
        :icon="Check"
        @click="paramSubmit(paramsFormRef)"
      >
        提交
      </el-button>
    </div>
    <el-collapse class="paramsCollapse" v-model="activeNames">
      <el-collapse-item title="基本信息" name="1">
        <el-form
          ref="paramsFormRef"
          class="paramsForm"
          :rules="paramsRules"
          :inline="true"
          :model="paramsForm"
        >
          <el-form-item label="组织" prop="orgName">
            <el-tree-select
              v-model="paramsForm.orgName"
              :data="deptOptions"
              :props="{
                value: 'label',
                label: 'label',
                children: 'children',
              }"
              value-key="id"
              placeholder="请选择"
              check-strictly
              :default-expand-all="true"
              @node-click="selectDept"
            />
          </el-form-item>
          <el-form-item label="编码">
            <el-input
              v-model="paramsForm.assetCode"
              placeholder="编码"
              clearable
            />
          </el-form-item>
          <el-form-item label="是否可用" prop="flagEnabled">
            <el-select
              v-model="paramsForm.flagEnabled"
              placeholder="请选择是否可用"
            >
              <el-option
                v-for="dict in enabledFlag"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="名称" prop="assetName">
            <el-input
              v-model="paramsForm.assetName"
              placeholder="名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="类别" prop="assetType">
            <el-select
              v-model="paramsForm.assetType"
              placeholder="请选择类别"
              clearable
            >
              <el-option
                v-for="dict in dc_asset_attr"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="组成设备">
            <el-select
              v-model="paramsDevice"
              multiple
              filterable
              allow-create
              default-first-option
              :reserve-keyword="false"
              placeholder="组成设备"
              style="width: 240px"
            >
              <el-option
                v-for="item in deviceOption"
                :key="item.id"
                :label="item.deviceName"
                :value="item.centerDeviceCode"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="success" @click="selectParams">选择参数</el-button>
          </el-form-item>
        </el-form>
      </el-collapse-item>
      <el-collapse-item title="参数列表" name="2">
        <vxe-table
          class="tableCollapse"
          border
          ref="paramsTableRef"
          max-height="400"
          :row-config="{ isHover: true }"
          :loading="loading"
          :data="paramsList"
        >
          <vxe-column type="checkbox" width="60"></vxe-column>
          <vxe-column field="paramCode" title="参数编码"></vxe-column>
          <vxe-column
            field="paramName"
            title="参数名称"
            :filters="addressOptions"
            :filter-method="filterAddressMethod"
            :filter-recover-method="filterAddressRecoverMethod"
          >
            <template #filter="{ $panel, column }">
              <vxe-input
                class="filterInput"
                v-for="(option, index) in column.filters"
                :key="index"
                v-model="option.data"
                @input="$panel.changeOption($event, !!option.data, option)"
                @keyup.enter="$panel.confirmFilter()"
                placeholder="参数名称"
                size="mini"
              ></vxe-input>
            </template>
          </vxe-column>
          <vxe-column field="flagEnabled" title="是否有效">
            <template #default="{ row }">
              <vxe-checkbox v-model="row.flagEnabled"></vxe-checkbox>
            </template>
          </vxe-column>
          <vxe-column field="contrlFlag" title="是否可控">
            <template #default="{ row }">
              <vxe-checkbox v-model="row.contrlFlag"></vxe-checkbox>
            </template>
          </vxe-column>
        </vxe-table>
      </el-collapse-item>
    </el-collapse>
    <el-dialog
      class="addDialog"
      v-model="dialogTableVisible"
      title="选择参数"
      width="1200"
    >
      <vxe-table
        class="tableDialog"
        border
        ref="addTableRef"
        max-height="400"
        :row-config="{ isHover: true }"
        :loading="loading"
        :data="paramsData"
      >
        <vxe-column type="checkbox" width="60"></vxe-column>
        <vxe-column field="deviceUuid" title="设备编码" sortable></vxe-column>
        <vxe-column field="deviceName" title="设备名称"></vxe-column>
        <vxe-column field="paramCode" title="参数编码"></vxe-column>
        <vxe-column
          field="paramModelName"
          title="参数模版名称"
          :filters="ageOptions"
          :filter-method="filterAgeMethod"
          :filter-recover-method="filterAgeRecoverMethod"
        >
          <template #filter="{ $panel, column }">
            <vxe-input
              class="filterInput"
              v-for="(option, index) in column.filters"
              :key="index"
              v-model="option.data"
              @input="$panel.changeOption($event, !!option.data, option)"
              @keyup.enter="$panel.confirmFilter()"
              placeholder="参数模版名称"
              size="mini"
            ></vxe-input>
          </template>
        </vxe-column>
        <vxe-column
          field="paramName"
          title="参数名称"
          :filters="addressOptions"
          :filter-method="filterAddressMethod"
          :filter-recover-method="filterAddressRecoverMethod"
        >
          <template #filter="{ $panel, column }">
            <vxe-input
              class="filterInput"
              v-for="(option, index) in column.filters"
              :key="index"
              v-model="option.data"
              @input="$panel.changeOption($event, !!option.data, option)"
              @keyup.enter="$panel.confirmFilter()"
              placeholder="参数名称"
              size="mini"
            ></vxe-input>
          </template>
        </vxe-column>
        <vxe-column
          field="partion"
          title="分区"
          :filter-multiple="false"
          :filters="sexOptions"
        ></vxe-column>
      </vxe-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogTableVisible = false">取消</el-button>
          <el-button type="primary" @click="addConfirm"> 确认 </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted } from "vue";
import { useRoute } from "vue-router";
import { deptTreeSelect } from "@/api/system/user";
import { listByDeviceUuids } from "@/api/model/asset/params";
import { listDeviceNoPage } from "@/api/model/device";
import {
  listInfo,
  getInfo,
  delInfo,
  addInfo,
  updateInfo,
} from "@/api/model/asset/info";
import { Check } from "@element-plus/icons-vue";

const { proxy } = getCurrentInstance();
const { dc_asset_attr } = proxy.useDict("dc_asset_attr");

const activeNames = ref(["1", "2"]);
const route = useRoute();
const id = route.query.id;
const paramsFormRef = ref();
const dialogTableVisible = ref(false);
const deptOptions = ref([]);
const paramsData = ref([]);
const paramsList = ref([]);
const paramsCode = ref([]);
const paramsDevice = ref([]);
const deviceOption = ref([]);
const enabledFlag = ref([
  { label: "可用", value: 1, elTagType: "default", elTagClass: null },
  { label: "不可用", value: 0, elTagType: "default", elTagClass: null },
]);
const paramsForm = reactive({
  assetCode: "",
  flagEnabled: null,
  assetName: "",
  assetType: "",
  orgCode: null,
  orgName: "",
  assetParamsDtos: [
    {
      paramCode: "",
      flagEnabled: false,
      contrlFlag: false,
    },
  ],
});
const paramsTableRef = ref();
const addTableRef = ref();
const loading = ref(false);
const sexOptions = ref([
  { label: "高区", value: "高区" },
  { label: "中区", value: "中区" },
  { label: "低区", value: "低区" },
]);
const ageOptions = ref([{ data: "" }]);
const addressOptions = ref([{ data: "" }]);
const paramsRules = reactive({
  assetName: [{ required: true, message: "请输入资产名称", trigger: "blur" }],
});

const filterAgeMethod = ({ option, row }) => {
  return row.age === Number(option.data);
};
const filterAgeRecoverMethod = ({ option }) => {
  // 如果是自定义筛选模板，当为点击确认时，该选项将被恢复为默认值
  option.data = "";
};
const filterAddressMethod = ({ option, row }) => {
  return row.address === option.data;
};
const filterAddressRecoverMethod = ({ option }) => {
  // 如果是自定义筛选模板，当为点击确认时，该选项将被恢复为默认值
  option.data = "";
};
onMounted(() => {
  const dsfsdf = route.query.id;
  debugger;
  getDeptTree();
  getDevice();
});
function getDeptTree() {
  //获取部门树
  deptTreeSelect().then((response) => {
    deptOptions.value = response.data;
  });
}
function getDevice() {
  //获取部门树
  listDeviceNoPage().then((response) => {
    deviceOption.value = response.data;
  });
}

function selectParams() {
  //选择参数
  if (paramsDevice.value.length != 0) {
    const params = {
      deviceUuids: paramsDevice.value,
      excludeParamCodes: [],
    };
    listByDeviceUuids(params).then((res) => {
      if (res.code === 200) {
        paramsData.value = res.data;
        dialogTableVisible.value = true;
      }
    });
  }
}
function selectDept(val) {
  //部门参数选择
  paramsForm.orgCode = val.id;
}
function addConfirm() {
  //选择参数确认
  const $addTable = addTableRef.value;
  if ($addTable) {
    const selectRecords = $addTable.getCheckboxRecords();
    paramsList.value = selectRecords.map((item) => {
      return {
        ...item,
        flagEnabled: false,
        contrlFlag: false,
      };
    });
    paramsCode.value = selectRecords.map((item) => item.paramCode);
    dialogTableVisible.value = false;
  }
}

const paramSubmit = async (formEl) => {
  //提交
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const $submitTable = paramsTableRef.value;
      if ($submitTable) {
        const selectParamsList = $submitTable.getCheckboxRecords();
        const selectParamsListArr = selectParamsList.map((item) => ({
          paramCode: item.paramCode,
          flagEnabled: item.flagEnabled,
          contrlFlag: item.contrlFlag,
        }));
        paramsForm.assetParamsDtos = selectParamsListArr;
        if (id.value != undefined) {
          updateInfo(paramsForm).then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
            getList();
          });
        } else {
          addInfo(paramsForm).then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
            getList();
          });
        }
        console.log(paramsForm);
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};
</script>
<style scoped>
.paramsCollapse {
  .tableCollapse {
    .filterInput {
      width: 120px;
      margin: 10px;
    }
  }
}
:deep(.addDialog) {
  .tableDialog {
    .filterInput {
      width: 120px;
      margin: 10px;
    }
  }
}
</style>
