<template>
  <layout-card>
    <el-form
      ref="formRef"
      :rules="rules"
      :model="data.form"
      label-width="120px"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item label="安全例会标题" prop="SAFETY_MEETING_TITLE">
            <el-input
              v-model="data.form.SAFETY_MEETING_TITLE"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-divider content-position="left">涉及人</el-divider>
        </el-col>
        <el-col :span="24">
          <el-form-item class="end">
            <el-button type="primary" @click="fnAddPeople">添加</el-button>
          </el-form-item>
        </el-col>
        <template v-for="(item, index) in data.form.people" :key="item.id">
          <el-col :span="8">
            <el-form-item
              :label="'部门' + (index + 1)"
              :prop="'people.' + index + '.DEPARTMENT_ID'"
              :rules="{
                required: true,
                message: '部门不能为空',
                trigger: 'blur',
              }"
            >
              <layout-department
                v-model="item.DEPARTMENT_ID"
                @update:model-value="
                  fnDepartmentChange($event, index, 'people')
                "
              />
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              :label="'岗位' + (index + 1)"
              :prop="'people.' + index + '.POST_ID'"
              :rules="{
                required: true,
                message: '岗位不能为空',
                trigger: 'blur',
              }"
            >
              <el-select
                :model-value="item.POST_ID"
                @change="fnPostChange($event, index, 'people')"
              >
                <el-option
                  v-for="item1 in item.postList"
                  :key="item1.POST_ID"
                  :label="item1.NAME"
                  :value="item1.POST_ID"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item
              :label="'人员' + (index + 1)"
              :prop="'people.' + index + '.USER_ID'"
              :rules="{
                required: true,
                message: '人员不能为空',
                trigger: 'blur',
              }"
            >
              <div
                style="
                  flex: 1;
                  display: flex;
                  justify-content: space-between;
                  align-items: flex-start;
                "
              >
                <el-select v-model="item.USER_ID" multiple>
                  <el-option
                    v-for="item1 in item.userList"
                    :key="item1.USER_ID"
                    :label="item1.NAME"
                    :value="item1.USER_ID"
                  />
                </el-select>
                <el-button
                  class="ml-10"
                  type="primary"
                  @click="fnSelectAll(item)"
                >
                  {{ item.USER_ID.length > 0 ? "取消所有选中" : "全选" }}
                </el-button>
                <el-button
                  v-if="index !== 0"
                  class="ml-10"
                  type="danger"
                  @click="data.form.people.splice(index, 1)"
                >
                  删除
                </el-button>
              </div>
            </el-form-item>
          </el-col>
        </template>
        <el-col :span="24">
          <el-divider content-position="left">安全例会内容</el-divider>
        </el-col>
        <el-col :span="24">
          <el-form-item label="正文" prop="TEXT">
            <el-input
              v-model="data.form.SAFETY_MEETING_CONTENT"
              type="textarea"
              :autosize="{ minRows: 3 }"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-divider content-position="left">安全例会附件</el-divider>
        </el-col>
        <el-col :span="24">
          <el-form-item label="添加附件" prop="file">
            <layout-upload
              v-model:file-list="data.form.file"
              accept=".jpg,.jpeg,.png"
              list-type="picture-card"
              delete-to-server
              :limit="99"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="mt-10 tc">
      <el-button type="primary" @click="fnSubmit">提交</el-button>
    </div>
  </layout-card>
</template>

<script setup>
import { reactive, ref } from "vue";
import LayoutUpload from "@/components/upload/index.vue";

import LayoutDepartment from "@/components/department/index.vue";
import { getPostListAll, getUserListAll } from "@/request/data_dictionary.js";
import {
  addingPrefixToFile,
  verifyDuplicateSelection,
} from "@/assets/js/utils.js";
import { debounce } from "throttle-debounce";
import { useRoute, useRouter } from "vue-router";
import useFormValidate from "@/assets/js/useFormValidate.js";
import { ElMessage } from "element-plus";
import {
  getSafetyMeetingView,
  setSafetyMeetingEdit,
  setSafetyMeetingData,
} from "@/request/safety_meeting.js";
import { uniqBy } from "lodash-es";
import { setUploadImg } from "@/request/api.js";

const route = useRoute();
const router = useRouter();
const { SAFETY_MEETING_ID } = route.query;
const rules = {
  PROMISE_NAME: [
    { required: true, message: "安全例会名称不能为空", trigger: "blur" },
  ],
};
const formRef = ref(null);
const data = reactive({
  form: {
    people: [],
    file: [],
  },
});
const fnAddPeople = () => {
  data.form.people.push({
    postList: [],
    userList: [],
    DEPARTMENT_ID: "",
    POST_ID: "",
    USER_ID: [],
    id: Math.random(),
  });
};
const fnGetData = async () => {
  if (!SAFETY_MEETING_ID) {
    fnAddPeople();
    return;
  }
  const resData = await getSafetyMeetingView({ SAFETY_MEETING_ID });
  const people = resData.people;
  const newPeople = [];
  for (let i = 0; i < people.length; i++) {
    newPeople.push({
      ...people[i],
      postList: [],
      userList: [],
      USER_ID: [],
      id: people[i].SAFETY_MEETING_PEOPLE_ID,
    });
    for (let j = 0; j < newPeople.length; j++) {
      if (people[i].POST_ID === newPeople[j].POST_ID) {
        newPeople[j].USER_ID.push(people[i].USER_ID);
      }
    }
  }
  data.form = {
    ...resData.pd,
    people: uniqBy(newPeople, "POST_ID"),
  };
  if (resData.imgs) {
    data.form.file = addingPrefixToFile(resData.imgs);
  }
  for (let i = 0; i < data.form.people.length; i++) {
    await fnGetPostList(data.form.people[i].DEPARTMENT_ID, i, "people");
    await fnGetUserList(
      data.form.people[i].DEPARTMENT_ID,
      data.form.people[i].POST_ID,
      i,
      "people"
    );
  }
};
fnGetData();
const fnDepartmentChange = (value, index, key) => {
  data.form[key][index].POST_ID = "";
  data.form[key][index].USER_ID = [];
  data.form[key][index].postList = [];
  data.form[key][index].userList = [];
  fnGetPostList(value, index, key);
};
const fnGetPostList = async (DEPARTMENT_ID, index, key) => {
  const resData = await getPostListAll({ DEPARTMENT_ID });
  data.form[key][index].postList = resData.postList;
};
const fnPostChange = async (value, index, key) => {
  await verifyDuplicateSelection(data.form[key], index, "POST_ID", value);
  data.form[key][index].USER_ID = [];
  data.form[key][index].userList = [];
  await fnGetUserList(data.form[key][index].DEPARTMENT_ID, value, index, key);
};
const fnGetUserList = async (DEPARTMENT_ID, POST_ID, index, key) => {
  const resData = await getUserListAll({ DEPARTMENT_ID, POST_ID });
  data.form[key][index].userList = resData.userList;
};

const fnSelectAll = async (item) => {
  if (item.USER_ID.length > 0) {
    item.USER_ID = [];
  } else {
    item.USER_ID = item.userList.map((item) => item.USER_ID);
  }
};

const fnSubmit = debounce(
  1000,
  async () => {
    await useFormValidate(formRef);
    const people = data.form.people.map((item) => ({
      DEPARTMENT_ID: item.DEPARTMENT_ID,
      POST_ID: item.POST_ID,
      USER_ID: item.USER_ID,
    }));
    const params = {
      ...data.form,
      people: JSON.stringify(people),
      SAFETY_MEETING_ID,
    };
    const resData = !SAFETY_MEETING_ID
      ? await setSafetyMeetingData(params)
      : await setSafetyMeetingEdit(params);
    const formData = new FormData();
    if (data.form.file) {
      for (let i = 0; i < data.form.file.length; i++) {
        if (data.form.file[i].raw)
          formData.append("FFILE", data.form.file[i].raw);
      }
      formData.append("FOREIGN_KEY", resData.SAFETY_MEETING_ID);
      formData.append("TYPE", 105);
      await setUploadImg(formData);
    }
    ElMessage.success("操作成功");
    router.back();
  },
  { atBegin: true }
);
</script>

<style scoped lang="scss"></style>
