<template>
  <div class="pageIndexClass">
    <byTable :hideTable="true" :hidePagination="true" :source="sourceList.data" :pagination="sourceList.pagination" :config="config" :loading="false"
             highlight-current-row :action-list="[
        {
          text: '添加',
          action: () => openModal(),
        },
      ]" @get-list="getList">
    </byTable>
    <div style="padding: 0 20px 20px 20px; background-color: white">
      <el-table v-loading="loading" :data="sourceList.data" row-key="id" :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
                default-expand-all>
        <el-table-column prop="subjectsName" label="名称" />
        <el-table-column prop="calculateItemName" label="核算项目名称" />
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="sort" label="排序" width="100" />
        <el-table-column label="创建时间" align="left" prop="createTime" width="160">
        </el-table-column>
        <el-table-column label="操作" align="center" width="200">
          <template #default="{ row }">
            <el-button link type="primary" @click="getDtl(row)">修改</el-button>
            <el-button link type="primary" @click="openModal(row)">添加子项</el-button>
            <!-- <el-button link type="primary" @click="openRoomModal(row)">权限</el-button> -->
            <el-button link type="primary" @click="listDelete(row)">删除</el-button>
            <!-- v-if="checkIsTopData(row.parentId)" -->
          </template>
        </el-table-column>
      </el-table>
    </div>

    <el-dialog :title="modalType == 'add' ? '添加科目' : '编辑科目'" v-if="dialogVisible" v-model="dialogVisible" width="500" v-loading="loadingDialog">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
        <!-- <template #parentId>
          <div style="width: 100%">
            <el-tree-select v-model="formData.data.parentId" :data="sourceList.data" :disabled="modalType=='edit'" check-strictly
                            :render-after-expand="false" node-key="deptId" :props="defaultProps" style="width:100%" />
          </div>
        </template> -->
        <!-- <template #orderNum>
          <div style="width: 100%">
            <el-input-number v-model="formData.data.orderNum" placeholder="请输入排序" style="width: 100%" :precision="0" :controls="false" :min="0"
                             :max="99999" />
          </div>
        </template> -->
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="default">取 消</el-button>
        <el-button type="primary" @click="submitForm()" size="default">确 定</el-button>
      </template>
    </el-dialog>

    <el-dialog title="权限配置" v-if="roomDialogVisible" v-model="roomDialogVisible" width="500" v-loading="loading">
      <el-tree :data="treeData" show-checkbox node-key="id" :default-checked-keys="checkTreeData" :props="defaultPropsOne" ref="tree"> </el-tree>
      <template #footer>
        <el-button @click="roomDialogVisible = false" size="default">取 消</el-button>
        <el-button type="primary" @click="submitTree()" size="default" :loading="submitLoading">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { computed, ref, watch } from "vue";
import byTable from "@/components/byTable/index";
import { ElMessage, ElMessageBox } from "element-plus";
import byForm from "@/components/byForm/index";
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance();

const defaultProps = {
  children: "children",
  label: "subjectsName",
};
const defaultPropsOne = {
  children: "children",
  label: "label",
};
const userList = ref([]);
const paymentTypeData = ref([]);
const typeList = ref([
  {
    label: "公司",
    value: 0,
  },
  // {
  //   label: "业务中心",
  //   value: 1,
  // },
  {
    label: "科目",
    value: 2,
  },
  {
    label: "组",
    value: 3,
  },
]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 9999,
    keyword: "",
    tenantId: useUserStore().user.tenantId,
  },
});
const loading = ref(false);
const config = computed(() => {
  return [];
});
const getDict = () => {
  // proxy
  //   .get("/tenantUser/list", {
  //     pageNum: 1,
  //     pageSize: 10000,
  //     tenantId: useUserStore().user.tenantId,
  //   })
  //   .then((res) => {
  //     userList.value = res.rows.map((item) => {
  //       return {
  //         label: item.nickName,
  //         value: item.userId,
  //       };
  //     });
  //   });

  proxy.post("/paymentType/page", { pageNum: 1, pageSize: 999 }).then((res) => {
    paymentTypeData.value = res.rows.map((item) => {
      return {
        ...item,
        label: item.name,
        value: item.id,
      };
    });
  });
};
const deptAllData = ref([]);
const getList = (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/accountSubjects/list", sourceList.value.pagination)
    .then((res) => {
      deptAllData.value = res;
      sourceList.value.data = proxy.handleTree(res, "id");
      setTimeout(() => {
        loading.value = false;
      }, 200);
    });
};
getDict();
getList();
const modalType = ref("add");
const dialogVisible = ref(false);
const loadingDialog = ref(false);
const submit = ref(null);
const formOption = reactive({
  inline: true,
  labelWidth: 110,
  itemWidth: 100,
  rules: [],
});
const formData = reactive({
  data: {},
});
const formConfig = computed(() => {
  return [
    // {
    //   type: "slot",
    //   prop: "parentId",
    //   slotName: "parentId",
    //   label: "上级科目",
    // },
    {
      type: "input",
      prop: "subjectsName",
      label: "名称",
    },
    {
      type: "input",
      prop: "subjectsCode",
      label: "代码",
    },
    // {
    //   type: "select",
    //   label: "收付款类型",
    //   prop: "paymentTypeId",
    //   itemWidth: 100,
    //   data: paymentTypeData.value,
    //   // clearable: true,
    //   fn: (val) => {},
    // },
    {
      type: "input",
      prop: "calculateItemName",
      label: "核算项目名称",
    },
    // {
    //   type: "slot",
    //   prop: "orderNum",
    //   slotName: "orderNum",
    //   label: "科目排序",
    // },
    {
      type: "number",
      prop: "sort",
      label: "排序",
      precision: 0,
      min: 0,
      controls: false,
      // itemWidth: 50,
      disabled: false,
    },
    {
      type: "input",
      itemType: "textarea",
      prop: "remark",
      label: "备注",
    },
  ];
});
const rules = ref({
  subjectsName: [{ required: true, message: "请输入名称", trigger: "blur" }],
  subjectsCode: [{ required: true, message: "请输入代码", trigger: "blur" }],
  sort: [{ required: true, message: "请输入科目排序", trigger: "blur" }],
  paymentTypeId: [
    { required: true, message: "请选择收费款类型", trigger: "change" },
  ],
});
const disabledType = ref(false);
const openModal = (row) => {
  disabledType.value = false;
  modalType.value = "add";
  formData.data = {
    parentId: "",
  };
  if (row && row.id) {
    formData.data.parentId = row.id;
  }
  loadingDialog.value = false;
  dialogVisible.value = true;
};

const submitForm = () => {
  submit.value.handleSubmit(() => {
    loadingDialog.value = true;
    proxy
      .post("/accountSubjects/" + modalType.value, formData.data)
      .then(() => {
        proxy.msgTip("操作成功", 1);
        dialogVisible.value = false;
        getList();
      });
  });
};

const listDelete = (row) => {
  proxy
    .msgConfirm()
    .then((res) => {
      proxy
        .post("/accountSubjects/delete", {
          id: row.id,
        })
        .then((res) => {
          proxy.msgTip("操作成功", 1);
          getList();
        });
    })
    .catch((err) => {});
};
const isTopData = ref(false);
const checkIsTopData = (parentId) => {
  return deptAllData.value.some((x) => x.id == parentId);
};

const getDtl = (row) => {
  formData.data = proxy.deepClone(row);
  modalType.value = "edit";
  dialogVisible.value = true;
};

const tree = ref(null);
const roomDialogVisible = ref(false);
const treeData = ref([]);
const checkTreeData = ref([]);
const rowTenantId = ref("");
const getSubset = (list, data) => {
  for (let i = 0; i < list.length; i++) {
    if (list[i].children && list[i].children.length > 0) {
      getSubset(list[i].children, data);
    } else {
      data.push(list[i].id);
    }
  }
  return data;
};
const openRoomModal = (row) => {
  if (row.parentId == "0") {
    rowTenantId.value = row.tenantId;
  } else {
    rowTenantId.value = row.deptId;
  }
  proxy
    .get("/tenantInfo/roleMenuTreeSelect/" + rowTenantId.value)
    .then((res) => {
      if (res.code == 200) {
        treeData.value = res.menus;
        let data = getSubset(res.menus, []);
        checkTreeData.value = res.checkedKeys.filter((item) => {
          return data.some((i) => item == i);
        });
        roomDialogVisible.value = true;
      }
    });
};
const noRepeat = (arr) => {
  var newArr = [...new Set(arr)];
  return newArr;
};

const submitTree = () => {
  let data = noRepeat(
    tree.value.getHalfCheckedKeys().concat(tree.value.getCheckedKeys())
  );
  if (data.length == 0) {
    ElMessage({
      message: "请至少选择一个菜单",
      type: "error",
    });
    return;
  }
  proxy
    .post("/tenantInfo/bindingMenu", {
      tenantId: rowTenantId.value,
      menuIdList: data,
    })
    .then((res) => {
      ElMessage({
        message: "保存成功",
        type: "success",
      });
      roomDialogVisible.value = false;
    });
};
</script>

<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>
