<template>
  <div class="app-container">
    <div class="submitBtn">
      <el-button
        type="primary"
        :icon="submitIcon"
        @click="paramSubmit(paramsFormRef)"
      >
        {{ paramsText }}
      </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="formData.paramsForm"
        >
          <el-form-item label="组织" prop="orgName">
            <el-tree-select
              v-model="formData.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="编码" prop="assetCode">
            <el-input
              v-model="formData.paramsForm.assetCode"
              placeholder="编码"
              clearable
            />
          </el-form-item>
          <el-form-item label="是否可用" prop="flagEnabled">
            <el-select
              v-model="formData.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="formData.paramsForm.assetName"
              placeholder="名称"
              clearable
            />
          </el-form-item>
          <el-form-item label="类别" prop="assetType">
            <el-select
              v-model="formData.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>
          <div>
            <el-form-item label="组成设备">
              <el-select
                v-model="paramsDevice"
                multiple
                filterable
                allow-create
                default-first-option
                collapse-tags
                collapse-tags-tooltip
                :max-collapse-tags="3"
                :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>
          </div>
        </el-form>
      </el-collapse-item>
      <el-collapse-item title="参数列表" name="2">
        <vxe-toolbar>
          <template #buttons>
            <vxe-button
              status="danger"
              content="删除"
              icon="vxe-icon-delete"
              @click="removeEvent()"
            ></vxe-button>
          </template>
        </vxe-toolbar>
        <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="filterParamName"
            :filter-recover-method="filterParamNameRecover"
          >
            <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-column title="操作" width="100" show-overflow>
            <template #default="{ row }">
              <vxe-button
                type="text"
                icon="vxe-icon-delete"
                @click="removeEvent(row)"
              ></vxe-button>
            </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="filterParamModel"
          :filter-recover-method="filterParamModelRecover"
        >
          <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="filterParamNameSel"
          :filter-recover-method="filterParamNameRecoverSel"
        >
          <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 { ElMessage } from "element-plus";
import { deptTreeSelect } from "@/api/system/user";
import {
  listByDeviceUuids,
  listParams,
  delParams,
} 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 router = useRouter();
const id = route.query.id;
const ids = ref();
const submitIcon = ref("Plus");
const paramsText = ref("新增");
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 formData = reactive({
  paramsForm: {
    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: "A", value: "A" },
  { label: "B", value: "B" },
  { label: "C", value: "C" },
  { label: "D", value: "D" },
]);
const ageOptions = ref([{ data: "" }]);
const addressOptions = ref([{ data: "" }]);
const paramsRules = reactive({
  orgName: [{ required: true, message: "请选择组织", trigger: "change" }],
  assetCode: [{ required: true, message: "请输入编码", trigger: "blur" }],
  flagEnabled: [
    { required: true, message: "请选择是否可用", trigger: "change" },
  ],
  assetName: [{ required: true, message: "请输入资产名称", trigger: "blur" }],
  assetType: [{ required: true, message: "请选择类别", trigger: "change" }],
});

const filterParamModel = ({ option, row }) => {
  //参数模板名称搜索
  return row.paramModelName === option.data;
};
const filterParamModelRecover = ({ option }) => {
  // 参数模板名称如果是自定义筛选模板，当为点击确认时，该选项将被恢复为默认值
  option.data = "";
};
const filterParamName = ({ option, row }) => {
  //参数名称搜索
  return row.paramName === option.data;
};
const filterParamNameRecover = ({ option }) => {
  // 参数名称如果是自定义筛选模板，当为点击确认时，该选项将被恢复为默认值
  option.data = "";
};
const filterParamNameSel = ({ option, row }) => {
  //选择参数名称搜索
  return row.paramName === option.data;
};
const filterParamNameRecoverSel = ({ option }) => {
  // 参数名称如果是自定义筛选模板，当为点击确认时，该选项将被恢复为默认值
  option.data = "";
};
onMounted(() => {
  if (route.query.id != undefined) {
    getBasicInfo();
    getParamsList();
  }
  getDeptTree();
  getDevice();
});
function getBasicInfo() {
  getInfo(route.query.id).then((response) => {
    formData.paramsForm = response.data;
    submitIcon.value = "Check";
    paramsText.value = "修改";
  });
}
function getParamsList() {
  //获取参数列表
  const params = {
    assetCode: route.query.assetCode,
  };
  listParams(params).then((res) => {
    if (res.code === 200) {
      paramsList.value = res.rows;
      paramsCode.value = paramsList.value.map((item) => item.paramCode);
    }
  });
}
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: paramsCode.value,
    };
    listByDeviceUuids(params).then((res) => {
      if (res.code === 200) {
        paramsData.value = res.data;
        dialogTableVisible.value = true;
      }
    });
  } else {
    ElMessage({
      message: "请先选择组成设备！",
      type: "warning",
    });
  }
}
function selectDept(val) {
  //部门参数选择
  formData.paramsForm.orgCode = val.id;
}
function addConfirm() {
  //选择参数确认
  const $addTable = addTableRef.value;
  if ($addTable) {
    const selectRecords = $addTable.getCheckboxRecords();
    selectRecords.map((item) => {
      paramsList.value.push({
        ...item,
        flagEnabled: false,
        contrlFlag: false,
      });
    });
    paramsCode.value = paramsList.value.map((item) => item.paramCode);
    console.log(paramsList.value, paramsCode.value);
    dialogTableVisible.value = false;
  }
}

const removeEvent = async (row) => {
  //删除
  if (row) {
    ids.value = row.id;
  } else {
    const $submitTable = paramsTableRef.value;
    ids.value = $submitTable.getCheckboxRecords().map((item) => item.id);
    if (ids.value.length === 0) {
      ElMessage({
        message: "请选择删除数据！",
        type: "warning",
      });
      return;
    }
  }
  if (route.query.id != undefined) {
    proxy.$modal
      .confirm("是否确认删除数据项？")
      .then(function () {
        return delParams(ids.value);
      })
      .then(() => {
        getParamsList();
        proxy.$modal.msgSuccess("删除成功");
      })
      .catch(() => {});
  } else {
    const $submitTable = paramsTableRef.value;
    const selectParamsList = $submitTable.getCheckboxRecords();
    if ($submitTable) {
      $submitTable.remove(row || selectParamsList);
      paramsList.value = $submitTable.getTableData().tableData;
      paramsCode.value = paramsList.value.map((item) => item.paramCode);
      console.log(paramsList.value);
    }
  }
};

const paramSubmit = async (formEl) => {
  //提交
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      const $submitTable = paramsTableRef.value;
      if ($submitTable) {
        if (route.query.id != undefined) {
          const selectParamsList = $submitTable.getCheckboxRecords();
          console.log(selectParamsList);
          const selectParamsListArr = selectParamsList.map((item) => ({
            id: item.id,
            paramCode: item.paramCode,
            flagEnabled: item.flagEnabled,
            contrlFlag: item.contrlFlag,
          }));
          formData.paramsForm.assetParamsDtos = selectParamsListArr;
          updateInfo(formData.paramsForm).then((response) => {
            proxy.$modal.msgSuccess("修改成功");
            open.value = false;
          });
        } else {
          const selectParamsList = $submitTable.getCheckboxRecords();
          const selectParamsListArr = selectParamsList.map((item) => ({
            paramCode: item.paramCode,
            flagEnabled: item.flagEnabled,
            contrlFlag: item.contrlFlag,
          }));
          formData.paramsForm.assetParamsDtos = selectParamsListArr;
          addInfo(formData.paramsForm).then((response) => {
            proxy.$modal.msgSuccess("新增成功");
            open.value = false;
          });
        }
        router.push({
          path: "AssetInfo",
        });
        console.log(formData.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>
