<template>
  <div class="feedback">
    
    <div class="content">
      <byTable
        :source="sourceList.data"
        :pagination="sourceList.pagination"
        :config="config"
        :loading="loading"
        highlight-current-row
        :selectConfig="selectConfig"
        searchKey="userName"
        :table-events="{
          //element talbe事件都能传
          select: select,
        }"
        :action-list="[
          {
            text: '添加反馈',
            action: () => openModal('add'),
          },
        ]"
        @get-list="getList">
        <template #slotName="{ item }">
          {{ item.createTime }}
        </template>
      </byTable>
    </div>
    <el-dialog :title="modalType == 'add' ? '添加反馈' : '编辑反馈'" v-if="dialogVisible" 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="large">取 消</el-button>
        <el-button type="primary" @click="submitForm('byform')" size="large" :loading="submitLoading"> 确 定 </el-button>
      </template>
    </el-dialog>
    <el-dialog title="修改密码" v-model="roomDialogVisible" width="300" :before-close="handleClose" v-loading="loading">
      <template #footer>
        <el-input v-model="password" type="password" placeholder="请输入新密码" show-password style="margin-bottom: 20px" />
        <el-button @click="roomDialogVisible = false" size="large">取 消</el-button>
        <el-button type="primary" @click="submitPassword(password)" size="large" :loading="submitLoading"> 确 定 </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
/* 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);
let modalType = ref("add");
const validatePass = (rule, value, callback) => {
  if (!formData.data.password && modalType.value == "add") {
    callback(new Error("请输入账号和密码"));
  } else {
    callback();
  }
};
let rules = ref({
  name: [{ required: true, message: '请填写姓名' }],
	companyName: [{ required: true, message: '请填写公司名称' }],
	contactInformation: [{ required: true, message: '请填写联系方式' }],
	problemStatement: [{ required: true, message: '请填写备注' }],
});

const userId = ref("");
const { proxy } = getCurrentInstance();
const password = ref("");
const roomDialogVisible = ref(false);
const selectConfig = computed(() => {
  return [];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "公司名称",
        prop: "companyName",
      },
    },
    {
      attrs: {
        label: "联系方式",
        prop: "contactInformation",
        align: "left",
      },
    },
    {
      attrs: {
        label: "模块名称",
        prop: "moduleType",
      },
    },
    {
      attrs: {
        label: "问题描述",
        prop: "problemStatement",
      },
    },
    {
      attrs: {
        label: "是否回复",
        prop: "status",
      },
      render(status) {
        return status == 1 ? "是" : "否";
      },
    },
    {
      attrs: {
        label: "操作",
        width: "200",
        align: "right",
      },
      // 渲染 el-button，一般用在最后一列。
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "修改",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              
              getDtl(row);
            },
          },
          {
            attrs: {
              label: "删除",
              type: "danger",
              text: true,
            },
            el: "button",
            click() {
              // 弹窗提示是否删除
              ElMessageBox.confirm("此操作将永久删除该数据, 是否继续?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
              }).then(() => {
                // 删除
                proxy
                  .post(
                    "/tenantUser/" + row.userId,
                    {
                      id: row.userId,
                    },
                    "delete"
                  )
                  .then((res) => {
                    ElMessage({
                      message: "删除成功",
                      type: "success",
                    });
                    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: "input",
      prop: "name",
      label: "姓名",
      required: true,
      itemWidth: 50,
      //disabled:true,
      itemType: "text",
    },
    {
      type: "treeSelect",
      prop: "moduleType",
      label: "模块名称",
      data: [],
    },
    {
      type: "input",
      prop: "companyName",
      label: "公司名称",
      required: true,
    },
    {
      type: "input",
      prop: "contactInformation",
      label: "联系方式",
      required: true,
    },
    {
      type: "input",
      prop: "problemStatement",
      label: "问题说明",
      required: true,
      itemType: "textarea",
    },

    
  ];
});
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 getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/problemFeedback/page", sourceList.value.pagination).then((message) => {
    message.rows.map((item) => {
      item.deptName = item.dept ? item.dept.deptName : item.dept;
    });
    sourceList.value.data = message.rows;
    sourceList.value.pagination.total = message.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};

//递归获取路由数据，初始化
const getRouterData = (data) => {
	data.forEach((item) => {
		item.label = item.meta.title
    item.id = item.meta.title
		if (item.children && item.children.length > 0) {
			getRouterData(item.children)
		}
	})
}

const getRouter = () => {
	proxy.get('getRouters', {}).then((res) => {
    console.log(res.data)
		getRouterData(res.data)
		for (let i = 0; i < res.data.length; i++) {
			const element = res.data[i]
			if (element.type == 2) {
				formConfig.value[1].data = element.children
			}
		}
	})
}
getRouter()

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(
        "/problemFeedback/" + modalType.value,
        {
          ...formData.data,
          tenantId: sourceList.value.pagination.tenantId,
        },
      )
      .then((res) => {
        ElMessage({
          message: modalType.value == "add" ? "添加成功" : "编辑成功",
          type: "success",
        });
        dialogVisible.value = false;
        getList();
      });
  });
};
const recursive = (data) => {
  data.map((item) => {
    item.label = item.deptName;
    item.id = item.deptId;
    if (item.children) {
      recursive(item.children);
    } else {
      item.children = [];
    }
  });
};

const submitPassword = (password1) => {
  if (!password1) {
    ElMessage({
      message: "请输入新密码",
      type: "warning",
    });
    return;
  }
  proxy
    .post(
      "/tenantUser/resetPwd",
      {
        password: password1,
        userId: userId.value,
      },
      "PUT"
    )
    .then((res) => {
      ElMessage({
        message: "重置成功",
        type: "success",
      });
      roomDialogVisible.value = false;
      password.value = "";
    });
};

const getDtl = (row) => {
  formData.data = { ...row};
    modalType.value = "edit";
    console.log(modalType.value);
    dialogVisible.value = true;
};
getList();
</script>

<style lang="scss" scoped>
.feedback {
  padding: 20px;
  display: flex;
  justify-content: space-between;

  

  .content {
    width: 100%;
  }
}
</style>
