<script setup lang="ts">
import { onMounted, reactive, ref, watch } from "vue";
import { FormInstance, FormRules, type CheckboxValueType } from "element-plus";
import {
  getOptionalBaseList,
  getRoleManageList,
  getUserList,
  createProcess,
  getFlowDetail
} from "@/api/business";
import { message } from "@/utils/message";
defineOptions({
  name: "UpdateForm"
});

const props = defineProps({
  updateFlag: {
    type: Boolean,
    default: false
  },
  updateId: {
    type: String,
    default: ""
  },
  closeDrawer: {
    type: Function
  }
});
const modalVisible = ref(false);

// 监听 props.message 的变化，并更新 modalVisible
watch(
  () => props.updateFlag,
  newValue => {
    modalVisible.value = newValue; // 更新 modalVisible
    if (newValue) {
      getFlowDetails(props.updateId);
    }
  }
);
const ruleFormRef = ref<FormInstance>();
const processForm = reactive({
  id: "",
  flowName: "",
  baseIdList: [],
  flowType: "",
  link: [
    {
      nodeName: "",
      roleId: null,
      userIdList: []
    }
  ],
  remark: ""
});
const checkAll = ref(false);
const indeterminate = ref(false);
const value = ref<CheckboxValueType[]>([]);
const subLibraryIdList = ref([]);
const roleNameList = ref([]);
const userNameList = ref([]);
const rules = reactive<FormRules>({
  flowName: [{ required: true, message: "请输入", trigger: "blur" }],
  baseIdList: [
    {
      required: true,
      message: "请选择",
      trigger: "change"
    }
  ],
  flowType: [
    {
      required: true,
      message: "请选择",
      trigger: "change"
    }
  ],
  nodeName: [{ required: true, message: "请输入", trigger: "blur" }],
  roleId: [
    {
      required: true,
      message: "请选择",
      trigger: "change"
    }
  ],
  userIdList: [
    {
      required: true,
      message: "请选择",
      trigger: "change"
    }
  ],
  remark: [{ required: true, message: "请输入", trigger: "blur" }]
});

watch(value, val => {
  if (val.length === 0) {
    checkAll.value = false;
    indeterminate.value = false;
  } else if (val.length === subLibraryIdList.value.length) {
    checkAll.value = true;
    indeterminate.value = false;
  } else {
    indeterminate.value = true;
  }
});

const handleCheckAll = (val: CheckboxValueType) => {
  indeterminate.value = false;
  if (val) {
    processForm.baseIdList = subLibraryIdList.value.map(_ => _.value);
  } else {
    processForm.baseIdList = [];
  }
};
// const submitForm = () => {
//   props.closeDrawer();
// };
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      // console.log(processForm);
      // console.log("submit!");
      const createForm = {
        id: processForm.id,
        flowName: processForm.flowName,
        remark: processForm.remark,
        flowType: "1",
        baseIdList: processForm.baseIdList,
        nodeInfoList: processForm.link.map(item => {
          return {
            id: "",
            userIdList: item.userIdList,
            order: "",
            nodeName: item.nodeName
          };
        })
      };
      // console.log(createForm);
      createProcess(createForm).then(res => {
        if (res.code === 200) {
          message("新建成功", { type: "success" });
          props.closeDrawer();
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
const handleDrawerClosed = () => {
  props.closeDrawer();
};
const addLink = () => {
  processForm.link.push({
    nodeName: "",
    roleId: null,
    userIdList: []
  });
};
const getOptionalBaseLists = async () => {
  const res: any = await getOptionalBaseList({
    flowType: ""
  });
  // console.log(res);
  if (res.code == 200) {
    subLibraryIdList.value = res.data;
  }
};
const getRoleManageLists = async () => {
  const res: any = await getRoleManageList({
    roleName: "",
    pageNum: "1",
    pageSize: "10"
  });
  // console.log(res);
  if (res.code == 200) {
    roleNameList.value = res.data.records;
  }
};
const getUserLists = async () => {
  const res: any = await getUserList({
    userName: "",
    deptId: "",
    roleId: "",
    pageNum: "1",
    pageSize: "10"
  });
  // console.log(res);
  if (res.code == 200) {
    userNameList.value = res.data.records;
  }
};
const handleSelect = async (value: any) => {
  // console.log(value);
  // const selectItem = JSON.parse(value);
  const res: any = await getUserList({
    userName: "",
    deptId: "",
    roleId: value,
    pageNum: "1",
    pageSize: "10"
  });
  // console.log(res);
  if (res.code == 200) {
    userNameList.value = res.data.records;
  }
};
const getFlowDetails = async (id: any) => {
  const res: any = await getFlowDetail({
    flowId: id
  });
  // console.log(res);
  processForm.id = res.data.id;
  processForm.flowName = res.data.flowName;
  processForm.remark = res.data.remark;
  processForm.flowType = res.data.flowType.toString();
  processForm.baseIdList = res.data.subLibraryIdList;
  processForm.link = res.data.nodeInfoList;
  // console.log(processForm);
  // if (res.code === 200) {
  //   // updateForm.value = res.data;
  //   updateFlag.value = true;
  // }
  // dataList.value = res.data;
};
onMounted(() => {
  getOptionalBaseLists();
  getRoleManageLists();
  getUserLists();
});
</script>

<template>
  <div>
    <el-drawer
      v-model="modalVisible"
      modal-class="drawer_content"
      :with-header="false"
      @closed="handleDrawerClosed"
    >
      <div class="drawer_header">
        <span>编辑流程</span>
      </div>
      <div class="drawer_box">
        <el-form
          :model="processForm"
          label-width="auto"
          :rules="rules"
          ref="ruleFormRef"
        >
          <div class="text-[20px] text-[#333] font-bold mb-6">基本信息</div>
          <el-form-item label="流程名称" prop="flowName">
            <el-input
              v-model="processForm.flowName"
              autocomplete="off"
              placeholder="请输入"
            />
          </el-form-item>
          <el-form-item label="子库名称" prop="baseIdList">
            <el-select
              v-model="processForm.baseIdList"
              multiple
              clearable
              collapse-tags
              popper-class="custom-header"
              :max-collapse-tags="3"
              placeholder="请选择"
              class="w-[80%]"
            >
              <el-option
                v-for="item in subLibraryIdList"
                :key="item.baseId"
                :label="item.baseName"
                :value="item.baseId"
              />
            </el-select>
            <el-checkbox
              class="ml-6"
              v-model="checkAll"
              :indeterminate="indeterminate"
              @change="handleCheckAll"
            >
              全部
            </el-checkbox>
          </el-form-item>
          <el-form-item label="数据类型" prop="flowType">
            <el-radio-group v-model="processForm.flowType">
              <el-radio label="1">知识报送</el-radio>
              <el-radio label="2">知识删除</el-radio>
              <el-radio label="3">知识撤回</el-radio>
            </el-radio-group>
          </el-form-item>
          <div class="text-[20px] text-[#333] font-bold mb-6">流程设计</div>
          <div v-for="(item, index) in processForm.link" :key="index">
            <el-form-item
              label="环节名称"
              :prop="'link.' + index + '.nodeName'"
              :rules="{
                required: true,
                message: '请输入',
                trigger: 'blur'
              }"
            >
              <el-input
                v-model="item.nodeName"
                autocomplete="off"
                placeholder="请输入"
              />
            </el-form-item>
            <el-form-item label="负责人" required>
              <el-col :span="8">
                <el-form-item
                  :prop="'link.' + index + '.roleId'"
                  :rules="{
                    required: true,
                    message: '请选择',
                    trigger: 'change'
                  }"
                >
                  <el-select
                    v-model="item.roleId"
                    clearable
                    popper-class="custom-header"
                    placeholder="请选择"
                    class="w-[100%]"
                    @change="handleSelect"
                  >
                    <el-option
                      v-for="item in roleNameList"
                      :key="item.id"
                      :label="item.roleName"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="2" class="text-center" />
              <el-col :span="14">
                <el-form-item
                  :prop="'link.' + index + '.userIdList'"
                  :rules="{
                    required: true,
                    message: '请选择',
                    trigger: 'change'
                  }"
                >
                  <el-select
                    v-model="item.userIdList"
                    multiple
                    clearable
                    collapse-tags
                    popper-class="custom-header"
                    placeholder="请选择"
                    :max-collapse-tags="2"
                    class="w-[100%]"
                  >
                    <el-option
                      v-for="item in userNameList"
                      :key="item.id"
                      :label="item.username"
                      :value="item.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
            </el-form-item>
            <el-divider
              border-style="double"
              v-if="index < processForm.link.length - 1"
            />
          </div>
          <el-form-item label=" ">
            <el-button @click="addLink">+添加审批环节</el-button>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="processForm.remark" type="textarea" />
          </el-form-item>
        </el-form>
        <div class="drawer_footer">
          <el-button plain @click="resetForm(ruleFormRef)">重置</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)"
            >确定</el-button
          >
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<style lang="scss" scoped>
:deep(.el-drawer__body) {
  padding: 0 !important;
}

.drawer_content {
  .drawer_header {
    box-sizing: border-box;
    height: 96px;
    padding: 24px;
    line-height: 65px;
    border-bottom: 1px solid #e9e9e9;

    span {
      padding-left: 8px;
      font-size: 20px;
      border-left: 6px solid #0052d9;
    }
  }

  .drawer_box {
    box-sizing: border-box;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    height: calc(100vh - 96px);
    padding: 24px;

    .drawer_footer {
      display: flex;
      justify-content: flex-end;
    }
  }
}
</style>
