<template>
  <div class="app-container">
    <vxe-grid ref="gridRef" v-bind="gridConfig" @toolbar-button-click="toolbarBtnClick">
      <template #dept_f_d="{ data }">
        <TreeDept ref="treeDept" v-model="data.deptId" clearable />
      </template>
      <template #member_t_d="{ row }">
        <el-popover placement="bottom" width="200" trigger="click">
          <template #reference>
            <vxe-button type="text" status="primary" @click="onShow(row.id)">查看</vxe-button>
          </template>
          <div class="team-member-content" v-loading="loadingMember">
            <div
              :class="['team-item', item.type === 2 ? 'team-item-blue' : '']"
              v-for="item in teamMembers"
              :key="item.id"
            >
              <div class="team-label" v-if="item.type === 1">成员：</div>
              <div class="team-label" v-else-if="item.type === 2">团队长：</div>
              <div class="team-name">{{ item.doctorName }}</div>
            </div>
          </div>
        </el-popover>
      </template>
      <template #operation_t_d="{ row }">
        <vxe-button type="text" status="primary" @click="onEditTeam(row.id)">编辑</vxe-button>
        <vxe-button type="text" status="danger" @click="onDelTeam(row.id)">删除</vxe-button>
      </template>
    </vxe-grid>
    <CommonModal
      v-if="visible"
      :visible.sync="visible"
      :title="title"
      :position="{
        top: 50,
      }"
      :closeCb="closeCb"
    >
      <template #default>
        <div class="form-content">
          <el-form ref="formRef" :model="formData" :rules="rules" label-width="110px">
            <el-form-item label="团队名称：" prop="name" inline-message>
              <el-input v-model="formData.name" placeholder="请输入团队名称" size="small" />
            </el-form-item>
            <MemberForm
              :type="type"
              :rules="rules"
              :leader.sync="formData.leader"
              :users.sync="formData.users"
              @memberAdd="onMemberAdd"
              @memberDel="onMemberDel"
            />
          </el-form>
        </div>
      </template>
      <template #footer>
        <div class="btn-content">
          <el-button style="margin-right: 10px" @click="onClose">取消</el-button>
          <el-button type="primary" @click="onSubmit" :loading="isLoading">确定</el-button>
        </div>
      </template>
    </CommonModal>
  </div>
</template>
<script>
import { commonGridConfig1 } from "@/config/vxeGrid";
import {
  doctorTeamListApi,
  updateDoctorTeamApi,
  delDoctorTeamApi,
  getDoctorTeamMemberApi,
  detailTeamApi,
} from "@/api/hospital/teamManage/doctor";
import MemberForm from "./components//MemberForm.vue";
import TreeDept from "@/components/TreeDept";
import { requireReg } from "@/regular";
import { nanoid } from "nanoid";
export default {
  name: "DoctorTeam",
  components: {
    MemberForm,
    TreeDept,
  },
  data() {
    var validateLeader = (rule, value, callback) => {
      if (!value.id) {
        callback(new Error("请选择团队长"));
        return;
      }
      callback();
    };
    var validateUsers = (rule, value, callback) => {
      console.log("value=", value);
      if (!value) {
        callback(new Error("请选择成员"));
        return;
      }
      callback();
    };
    return {
      gridConfig: {
        ...commonGridConfig1,
        showOverflow: false,
        maxHeight: 600,
        formConfig: {
          titleColon: true,
          titleAlign: "right",
          titleWidth: "90px",
          data: {
            name: undefined,
            deptId: undefined,
          },
          items: [
            {
              field: "deptId",
              title: "科室名称",
              itemRender: {},
              slots: {
                default: "dept_f_d",
              },
            },
            {
              field: "name",
              title: "团队名称",
              itemRender: {
                name: "VxeInput",
                props: {
                  placeholder: "请输入团队名称",
                },
              },
            },
            {
              itemRender: {
                name: "VxeButtonGroup",
                options: [
                  { type: "submit", content: "搜索", status: "primary" },
                  { type: "reset", content: "重置" },
                ],
              },
            },
          ],
        },
        columns: [
          {
            type: "seq",
            title: "序号",
            width: 100,
          },
          {
            field: "name",
            title: "团队名称",
            minWidth: 200,
          },
          {
            field: "deptName",
            title: "科室名称",
            minWidth: 200,
          },
          {
            field: "cy",
            title: "成员",
            minWidth: 100,
            slots: {
              default: "member_t_d",
            },
          },
          {
            field: "operation",
            title: "操作",
            width: 200,
            fixed: "right",
            slots: {
              default: "operation_t_d",
            },
          },
        ],
        proxyConfig: {
          form: true,
          response: {
            result: "data.list",
            total: "data.page.total",
          },
          ajax: {
            query: ({ form, page }) => {
              console.log("form=", form);
              const { currentPage: pageNum, pageSize } = page;
              const queryParams = {
                pageNum,
                pageSize,
                ...form,
              };
              return doctorTeamListApi(queryParams);
            },
          },
        },
        toolbarConfig: {
          buttons: [
            {
              code: "add",
              name: "新增团队",
              status: "primary",
              icon: "vxe-icon--plus",
            },
          ],
        },
        type: 1,
        title: "新增团队",
      },
      visible: false,
      formData: {
        name: "",
        leader: {},
        users: [
          {
            nanoid: nanoid(),
            userId: null,
          },
        ],
      },
      rules: {
        name: [requireReg("请输入团队名称")],
        leader: [
          {
            validator: validateLeader,
          },
        ],
        userId: [
          {
            validator: validateUsers,
          },
        ],
      },
      isLoading: false,
      loadingMember: false,
      teamMembers: [],
    };
  },
  methods: {
    toolbarBtnClick({ code, button, $event }) {
      console.log("提交=", code, button, $event);
      if (code === "add") {
        this.type = 1;
        this.title = "新增团队";
        this.formData = {
          name: "",
          leader: {},
          users: [
            {
              nanoid: nanoid(),
              userId: null,
            },
          ],
        };
        this.visible = true;
      }
    },
    onMemberAdd(index) {
      console.log("index=", index);
      this.formData.users.splice(index + 1, 0, {
        nanoid: nanoid(),
      });
    },
    onMemberDel(index) {
      console.log("index=", index);
      this.formData.users.splice(index, 1);
    },
    closeCb() {
      this.formData = {
        name: "",
        leader: {},
        users: [
          {
            nanoid: nanoid,
            userId: "",
          },
        ],
      };
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
      });
    },
    onClose() {
      this.formData = {
        name: "",
        leader: {},
        users: [
          {
            nanoid: nanoid,
            userId: "",
          },
        ],
      };
      this.$nextTick(() => {
        this.$refs.formRef.clearValidate();
        this.visible = false;
      });
    },
    onSubmit() {
      this.$refs.formRef.validate(async (isValid) => {
        this.isLoading = true;
        if (!isValid) {
          this.isLoading = false;
          return;
        }
        const { name, leader, users, id } = this.formData;
        const params = {
          id: id ? id : undefined,
          name,
          leaderDoctorId: leader.id,
          ywxUserIds: users.filter(item => !!item.userId).map((item) => item.userId),
          // }
        };
        try {
          await updateDoctorTeamApi(params);
          this.$message.success("操作成功");
          this.visible = false;
          this.$nextTick(() => {
            this.$refs.gridRef.commitProxy("query");
          });
        } catch (err) {
        } finally {
          this.isLoading = false;
        }
      });
    },
    async onEditTeam(teamId) {
      const { data } = await detailTeamApi(teamId);
      console.log("data=", data);
      const { name, id, followTeamDoctors } = data;
      let leader = (followTeamDoctors || []).find((item) => item.type === 2) || {};
      let users =
        followTeamDoctors
          .filter((item) => item.type === 1)
          .map((item) => {
            return {
              ...item,
              userName: item.doctorName,
            };
          }) || [];
      this.formData = {
        id,
        name,
        leader: {
          ...leader,
          id: leader.doctorId,
        },
        users:
          users.length === 0
            ? [
                {
                  nanoid: nanoid(),
                  userId: null,
                },
              ]
            : users,
      };
      this.type = 2;
      this.title = "编辑团队";
      this.visible = true;
    },
    onDelTeam(id) {
      this.$modal
        .confirm("删除后团队成员将无法继续开展随访业务是否继续操作")
        .then(async () => {
          console.log("是否走进了这里");
          await delDoctorTeamApi(id);
          this.$message.success("操作成功");
          this.$nextTick(() => {
            this.$refs.gridRef.commitProxy("query");
          });
        })
        .catch(() => {});
    },
    async onShow(id) {
      this.loadingMember = true;
      try {
        const { data } = await getDoctorTeamMemberApi(id);
        this.teamMembers = data || [];
        console.log("this.teamMembers=", data);
      } catch (err) {
      } finally {
        this.loadingMember = false;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-form-item__error {
  line-height: 5px;
}
.btn-content {
  display: flex;
  justify-content: center;
}
.team-member-content {
  overflow: auto;
  display: flex;
  flex-direction: column;
  align-items: center;
  max-height: 200px;
  .team-item {
    display: flex;
    width: 100%;
    .team-label {
      width: 80px;
    }
    .team-name {
      flex: 1;
    }
  }
  .team-item-blue {
    color: #409eff;
  }
}
.form-content {
  overflow: auto;
  max-height: 400px;
}
</style>
