<template>
  <div class="user">
    <div class="tree">
      <treeList :data="treeListData" v-model="sourceList.pagination.tenantId" node-key="id" @change="treeChange">
      </treeList>
    </div>
    <div class="content">
      <byTable :source="sourceList.data" :pagination="sourceList.pagination" :config="config" :loading="loading" highlight-current-row
               :selectConfig="selectConfig" :table-events="{
					//element talbe事件都能传
					select: select,
				}" :action-list="[
					{
						text: '添加流程',
						action: () => openModal('add'),
						disabled: !sourceList.pagination.tenantId,
					},
				]" @get-list="getList">
        <template #slotName="{ item }">
          {{ item.createTime }}
        </template>

      </byTable>
    </div>
    <el-dialog :title="modalType == 'add' ? '新增' : '编辑'" v-model="dialogVisible" width="500" v-loading="loading">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="byform">
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="default">取 消</el-button>
        <el-button type="primary" @click="submitForm" size="default" :loading="submitLoading">
          确 定
        </el-button>
      </template>
    </el-dialog>
    <!-- 版本切换模态框 -->
    <el-dialog title="版本切换" v-model="versionVisible" width="500" v-loading="loading">
      <el-form>
        <el-form-item label="流程名称">
          <el-input v-model="formData.flowName" disabled placeholder="请输入流程名称"></el-input>
        </el-form-item>
        <el-form-item label="当前版本">
          <el-select v-model="formData.version" placeholder="请选择">
            <el-option v-for="item in versionList" :key="item.id" :label="'v' + item.versionNumber" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="versionVisible = false" size="default">取 消</el-button>
        <el-button type="primary" @click="changeVersion(formData.version)" size="default" :loading="submitLoading">
          确 定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>
    
  <script setup  name="ProcessConfig">
/* eslint-disable vue/no-unused-components */
import { ElMessage, ElMessageBox } from "element-plus";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import treeList from "@/components/treeList/index";
import { computed, defineComponent, ref } from "vue";
const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
  },
});
let dialogVisible = ref(false);
const versionVisible = ref(false);
let modalType = ref("add");
let rules = ref({
  roleKey: [{ required: true, message: "请选择部门", trigger: "blur" }],
  nickName: [{ required: true, message: "姓名不能为空", trigger: "blur" }],
  userName: [{ required: true, message: "用户名不能为空", trigger: "blur" }],
});
const { proxy } = getCurrentInstance();
const selectConfig = computed(() => {
  return [];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "功能模块",
        prop: "classifyName",
      },
    },
    {
      attrs: {
        label: "流程标识",
        prop: "flowKey",
      },
    },
    {
      attrs: {
        label: "流程名称",
        prop: "flowName",
      },
    },

    {
      attrs: {
        label: "当前版本",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "v" + row.versionNumber,
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              getVersionList(row);
            },
          },
        ];
      },
    },

    {
      attrs: {
        label: "操作",
        width: "200",
        align: "right",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "新建版本",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              getDtl(row);
            },
          },
        ];
      },
    },
  ];
});

let versionList = ref([]);

const getVersionList = (row) => {
  formData.flowName = row.flowName;
  formData.version = row.id;
  versionVisible.value = true;
  proxy
    .post("/flowDefinition/getVersionList", {
      flowKey: row.flowKey,
      tenantId: row.tenantId,
    })
    .then((message) => {
      versionList.value = message;
      console.log(versionList);
    });
};
const changeVersion = (id) => {
  if (!id) {
    ElMessage.error("请选择版本");
    return;
  }
  proxy
    .post("/flowDefinition/updateVersion", {
      id: id,
    })
    .then((message) => {
      ElMessage.success("切换成功");
      versionVisible.value = false;
      getList();
    });
};

let formData = reactive({
  data: {},
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const byform = ref(null);
const treeListData = ref([]);
const formConfig = computed(() => {
  return [
    {
      type: "select",
      label: "功能模块",
      prop: "titleTemplate",
      isLoad: {
        url: `/flowInfo/getClassifyList`,
        labelKey: "stringArray",
        labelVal: "stringArray",
        method: "post",
        resUrl: "",
      },
      fn: (data) => {
        getFlowList(data);
      },
    },
    {
      type: "select",
      label: "流程名称",
      prop: "flowInfoId",
      data: [],
    },
  ];
});

const getFlowList = (name) => {
  proxy
    .post("/flowInfo/page", {
      pageNum: 1,
      pageSize: 1000,
      status: 1,
      classifyName: name,
    })
    .then((message) => {
      formConfig.value[1].data = message.rows.map((item) => {
        return {
          label: item.flowName,
          value: item.id,
        };
      });
    });
};

const newPassword = () => {
  formData.data.password = generatePassword();
};
const generatePassword = () => {
  var length = 12,
    charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789",
    password = "";
  for (var i = 0, n = charset.length; i < length; ++i) {
    password += charset.charAt(Math.floor(Math.random() * n));
  }
  return password;
};

const getTreeList = () => {
  proxy.post("/tenantInfo/list").then((message) => {
    message.map((item) => {
      item.label = item.enterpriseName;
      item.id = item.tenantId;
      item.children = [];
    });

    treeListData.value = message;
    console.log(treeListData.value);
  });
};
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/flowDefinition/page", sourceList.value.pagination)
    .then((message) => {
      sourceList.value.data = message.rows;
      sourceList.value.pagination.total = message.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
    });
};

const treeChange = (e) => {
  console.log(e);
  sourceList.value.pagination.tenantId = e.id;
  getList({ tenantId: e.id });
};

const openModal = () => {
  dialogVisible.value = true;
  modalType.value = "add";
  formData.data = {
    userType: 1,
  };
};
const TreetenantId = ref("");
const selection = ref({
  data: [],
});
const select = (_selection, row) => {
  selection.value.data = _selection;
  console.log(_selection.length);
};

const tree = ref(null);
const submitForm = () => {
  byform.value.handleSubmit((valid) => {
    proxy
      .post("/flowDefinition/" + modalType.value, {
        ...formData.data,
        tenantId: sourceList.value.pagination.tenantId,
      })
      .then((res) => {
        ElMessage({
          message: modalType.value == "add" ? "添加成功" : "编辑成功",
          type: "success",
        });
        dialogVisible.value = false;
        getList();
      });
  });
};

const getDept = () => {
  proxy.get("/system/user/deptTree").then((res) => {
    //formConfig.value[0].data = res.data
  });
};

const router = useRouter();
const getDtl = (row) => {
  formData.data = { ...row };

  router.push({
    path: "processChart",
    query: {
      id: row.id,
      flowInfoId: row.flowInfoId,
      tenantId: row.tenantId,
    },
  });
};
getTreeList();
getList();
</script>
    
<style lang="scss" scoped>
.user {
  padding: 10px;
  display: flex;
  justify-content: space-between;
  .tree {
    width: 300px;
  }
  .content {
    width: calc(100% - 310px);
  }
}
</style>