<template>
  <div class="bigBox" ref="bigBox">
    <MOSTY.FromPage :title="props.title" @closeDialog="handleClose">
      <template #content>
        <el-form class="mosty-from-wrap" label-suffix="：" ref="ruleFormRef" label-width="130px" :model="formData"
          :inline="true" :rules="rules" :disabled="props.type == 'view'">
          <el-row style="width: 100%">
            <el-col :span="18">
              <el-form-item label="发布接收范围" prop="receivingRange">
                <section style="display: flex; align-items: center; width: 100%">
                  <el-checkbox-group v-model="formData.receivingRange" @change="handleRangeChange" class="ml-4"
                    style="width: 100%; display: flex; flex-wrap: wrap; gap: 20px;">
                    <el-checkbox :label="item.value" v-for="item in range" :key="item.value">{{ item.title
                      }}</el-checkbox>
                  </el-checkbox-group>
                </section>
              </el-form-item>

              <el-form-item v-if="formData.receivingRange.includes('04')" label="指定部门" prop="receiveDeptName">
                <el-input v-model="formData.receiveDeptName" :disabled="props.type == 'view'" placeholder="请选择下发接收部门"
                  clearable>
                  <template #append> <el-button @click="ChooesDdld('01')">选择</el-button></template>
                </el-input>
                <div v-if="formData.receiveDeptNameList && formData.receiveDeptNameList.length > 0"
                  style="margin-top: 8px;">
                  <el-tag v-for="(dept, index) in formData.receiveDeptNameList" :key="index" closable
                    @close="removeDept(index)" style="margin-right: 8px; margin-bottom: 4px;">
                    {{ dept }}
                  </el-tag>
                </div>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <addUserTc v-if="formData.receivingRange.includes('05')" @choose="addUserChange" />
      </template>
      <template #footer>
        <el-button type="primary" @click="submit(ruleFormRef)" v-loading="saveloading">
          <el-icon>
            <DocumentChecked />
          </el-icon>
          <span>发布学习</span>
        </el-button>
        <el-button @click="handleClose">
          <el-icon>
            <DocumentDelete />
          </el-icon>
          <span>关闭</span>
        </el-button>
      </template>
      <template #dwbox>
        <ChooseDept :data="taskList" :showDdld="showDept" :searchType="'01'" @closezzjg="closeJhss" :Isstrictly="true"
          :disabledParent="true" @listdata="getSonValue" :zzlx="zzlx" />
      </template>
    </MOSTY.FromPage>
  </div>
</template>

<script setup>
import { watch, ref, getCurrentInstance, onMounted, nextTick, reactive, computed, h } from "vue"
import * as MOSTY from "@/components/MyComponents/index"
import ChooseDept from "@/components/MyComponents/ChooseDept/Departnobj.vue"
import { ElMessage, ElMessageBox } from "element-plus"
import { getApi, postApi } from "@/api/tobAcco_api.js"

import addUserTc from "./detailCom/addUser.vue"

const { proxy } = getCurrentInstance()
//点击下载二维码
const saveloading = ref(false)
const props = defineProps({
  type: {
    default: "",
    type: String
  },
  title: {
    default: "",
    type: String
  },
  id: {
    default: "",
    type: String
  }
})
/** 新增的人员 */
const addUserArr = ref([])
/** 是否展示 无分页的新增 */
const isShowAddUser = computed(() => {
  return formData.value.receivingRange.includes('05')
})

const rules = {
  receivingRange: [
    {
      validator: (rule, value, callback) => {
        if (!value || value.length === 0) {
          callback(new Error('请至少选择一个接收范围'))
        } else {
          callback()
        }
      },
      trigger: 'change'
    }
  ]
}

const formData = ref({
  receivingRange: [],
  receiveDeptIds: "",
  receiveDeptNames: "",
  receiveDeptName: "",
  receiveDeptNameList: [],
  receiveDeptId: "",
  receiveDeptIdList: []
})

const range = ref([
  { title: "各直属部门安全部门", value: "01" },
  { title: "全省各级安全部门成员", value: "02" },
  { title: "全体安全员", value: "03" },
  { title: "指定部门", value: "04" },
  { title: "指定人员", value: "05" },
  { title: "全省人员", value: "06" }
])

const zzlx = ref(null)
const showDept = ref(false)
const emits = defineEmits("close")
const ruleFormRef = ref()
const bigBox = ref()
const leaderid = ref("")
const singleShow = ref(false)
const chooseUserVisible = ref(false)
const taskList = ref([])
onMounted(() => {
  getRangeList()
})
// 获取下发范围列表
const getRangeList = async () => {
  try {
    const res = await getApi({}, "/mosty-jcgl/taskController/listSendRange")
    range.value = (res || []).map(item => ({ ...item, title: item.receivingRangeName, value: item.receivingRange }))
  } catch (e) {
    console.log(e)
  } finally {
  }
}
// 处理范围选择变化
const handleRangeChange = (val) => {
  // 如果取消选择了"指定部门"，清空部门相关数据
  if (!val.includes('04')) {
    formData.value.receiveDeptName = ""
    formData.value.receiveDeptNameList = []
    formData.value.receiveDeptId = ""
    formData.value.receiveDeptIdList = []
  }

  // 如果取消选择了"指定人员"，清空人员数据
  if (!val.includes('05')) {
    addUserArr.value = []
  }
}

watch(
  () => props.id,
  (val) => {
    if (props.id) {
      formData.value.id = props.id
      formData.value = {
        id: props.id,
        receivingRange: [],
        receiveDeptIds: "",
        receiveDeptNames: "",
        receiveDeptName: "",
        receiveDeptNameList: [],
        receiveDeptId: "",
        receiveDeptIdList: []
      }
    }
  },
  {
    immediate: true,
    deep: true
  }
)

//选择部门
const ChooesDdld = val => {
  zzlx.value = val
  if (val == "01") {
    showDept.value = true
  } else {
    leaderid.value = formData.value.responsibilityperson
    singleShow.value = true
    chooseUserVisible.value = true
  }
}

// 关闭单位部门弹框
const closeJhss = () => {
  taskList.value = []
  showDept.value = false
}

// 关闭弹框
const handleClose = () => {
  proxy.$modal
    .confirm("离开会丢失页面中修改的内容，确认离开吗？")
    .then(() => {
      formData.value = {
        id: props.id,
        receivingRange: [],
        receiveDeptIds: "",
        receiveDeptNames: "",
        receiveDeptName: "",
        receiveDeptNameList: [],
        receiveDeptId: "",
        receiveDeptIdList: []
      }
      emits("close")
    })
    .catch(() => {
      // catch error
    })
}

// 获取选择的部门
const getSonValue = value => {
  if (zzlx.value == "01") {
    // 清空原有数据
    formData.value.receiveDeptNameList = []
    formData.value.receiveDeptIdList = []

    value.forEach(item => {
      if (!formData.value.receiveDeptNameList.includes(item.orgName)) {
        formData.value.receiveDeptNameList.push(item.orgName)
      }
      if (!formData.value.receiveDeptIdList.includes(item.id)) {
        formData.value.receiveDeptIdList.push(item.id)
      }
    })

    // 更新字符串形式的数据
    formData.value.receiveDeptName = formData.value.receiveDeptNameList.join(",")
    formData.value.receiveDeptId = formData.value.receiveDeptIdList.join(",")

    // 确保接收范围包含"指定部门"
    if (!formData.value.receivingRange.includes('04')) {
      formData.value.receivingRange.push('04')
    }
  } else if (zzlx.value == "04") {
    formData.value.writer = value[0].userName
    formData.value.writerId = value[0].id
  }
}

// 移除部门标签
const removeDept = (index) => {
  formData.value.receiveDeptNameList.splice(index, 1)
  formData.value.receiveDeptIdList.splice(index, 1)

  // 更新字符串形式的数据
  formData.value.receiveDeptName = formData.value.receiveDeptNameList.join(",")
  formData.value.receiveDeptId = formData.value.receiveDeptIdList.join(",")

  // 如果没有部门了，从接收范围中移除"指定部门"
  if (formData.value.receiveDeptNameList.length === 0) {
    const index = formData.value.receivingRange.indexOf('04')
    if (index > -1) {
      formData.value.receivingRange.splice(index, 1)
    }
  }
}

// 保存
const submit = async (ruleFormRef) => {
  saveloading.value = true
  if (!ruleFormRef) return
  await ruleFormRef.validate(valid => {
    if (valid) {
      // 检查如果选择了"指定部门"，必须选择了至少一个部门
      if (formData.value.receivingRange.includes('04') &&
        (!formData.value.receiveDeptIdList || formData.value.receiveDeptIdList.length === 0)) {
        ElMessage.error("请选择至少一个部门")
        saveloading.value = false
        return
      }

      // 检查如果选择了"指定人员"，必须选择了至少一个人员
      if (formData.value.receivingRange.includes('05') &&
        (!addUserArr.value || addUserArr.value.length === 0)) {
        ElMessage.error("请选择至少一个人员")
        saveloading.value = false
        return
      }

      // 将数组数据转换为字符串
      if (Array.isArray(formData.value.receiveDeptIdList)) {
        formData.value.receiveDeptIds = formData.value.receiveDeptIdList.join(",")
      }
      if (Array.isArray(formData.value.receiveDeptNameList)) {
        formData.value.receiveDeptNames = formData.value.receiveDeptNameList.join(",")
      }

      if (Array.isArray(formData.value.files)) {
        formData.value.files = formData.value.files.toString()
      }

      const params = { ...formData.value }

      // 添加人员数据
      if (formData.value.receivingRange.includes('05') && addUserArr.value) {
        params.issuedUserIds = addUserArr.value.map(t => t.id).join(",")
        params.issuedUserNames = addUserArr.value.map(t => t.userName).join(",")
      }

      console.log("提交参数:", params)
      postApi(params, "/mosty-jcgl/lawRegulations/releaseLearning")
        .then(() => {
          ElMessage.success("发布成功")
          emits("close", true)
        })
        .finally(() => {
          saveloading.value = false
        })
    } else {
      ElMessageBox({
        title: "提示",
        message: h("p", null, [h("span", null, "请完善表单信息后在提交！")])
      })
      saveloading.value = false
    }
  })
}

const addUserChange = users => {
  addUserArr.value = users
}
</script>

<style lang="scss" scoped>
.table-lable {
  margin: 10px;
  color: var(--el-color-primary);
}

::v-deep ::-webkit-scrollbar {
  display: none !important;
}

::v-deep .el-pagination {
  justify-content: center !important;
}

::v-deep .el-image {
  margin: 0;
  padding: 1px;
}

.erweim {
  text-align: center;
  margin-right: 10px;

  >img {
    width: 148px;
    height: 148px;
    display: block;
    border: 1px solid var(--el-color-primary);
  }
}

.contents {
  width: 100%;
  margin: 10px auto;
}

::v-deep .el-form {
  margin: auto;
  padding: 10px;
  margin-top: 10px;
  flex-wrap: wrap;
  justify-content: start;
}

::v-deep .el-form-item__content {
  margin-left: 10px !important;
}

.el-form-item {
  display: flex;
  margin-right: 20px;
}

.bigBox {
  display: block !important;
  padding-right: 14px;
  box-sizing: border-box;
}

::v-deep .el-table .cell {
  padding: 0 0 !important;
}

::v-deep .el-table--border .el-table__cell .cell {
  padding-left: 0px !important;

  >input {
    width: 100%;
    height: 33px;
  }
}

.headBox {
  display: flex;
  justify-content: end;
  width: 100%;
  margin-bottom: 10px;
}

::v-deep .el-upload-list {
  width: 50%;
}

::v-deep .edui-default .edui-editor {
  width: 100% !important;
}

::v-deep .edui-default .edui-editor-iframeholder {
  width: 100% !important;
}

// 调整复选框组的样式
::v-deep .el-checkbox-group {
  .el-checkbox {
    color: #000;
    margin-right: 0;
  }
}
</style>