<template>
  <div class="bigBox" ref="bigBox">
    <MOSTY.FromPage :title="props.title" @closeDialog="handleClose">
      <template #content>
        <MOSTY.Assort :title="'督办任务信息'" />
        <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="24">
              <el-form-item label="任务标题" prop="title">
                <el-input v-model="formData.title" maxlength="100" placeholder="请输入任务标题"
                  :disabled="['feedback'].includes(props.type)" clearable />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row style="width: 100%">
            <el-col :span="24">
              <el-form-item label="任务内容" prop="content">
                <div class="contents">
                  <vue-ueditor-wrap v-model="formData.content" editor-id="editor" :config="editorConfig"
                    :editorDependencies="['ueditor.config.js', 'ueditor.all.js']" />
                </div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row style="width: 100%">
            <el-col :span="24">
              <el-form-item label="反馈期限" prop="feedBackDate">
                <el-date-picker v-model="formData.feedBackDate" format="YYYY-MM-DD" value-format="YYYY-MM-DD"
                  :disabled="['feedback'].includes(props.type)" type="date" placeholder="请选择日期" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row style="width: 100%">
            <el-col :span="24">
              <el-form-item label="反馈方式" prop="feedBackType">
                <section style="display: flex; align-items: center; width: 100%">
                  <el-radio-group v-model="formData.feedBackType" class="ml-4" style="width: 100%"
                    :disabled="['feedback'].includes(props.type)">
                    <el-radio :label="item.value" v-for="item in feedBackTypeRange" :key="item.value">{{ item.title
                      }}</el-radio>
                  </el-radio-group>
                </section>
              </el-form-item>
            </el-col>
          </el-row>

          <template v-if="['1', '2', '01', '02'].includes(formData.feedBackType) && !['feedback'].includes(props.type)">
            <el-row style="width: 100%" v-for="(item, index) in formData.values" :key="index">
              <el-col :span="24">
                <el-form-item :prop="'values.' + index + '.fieldKey'" :label="`数据项${index + 1}`"
                  :rules="[{ validator: (_rule, value, callback) => validate(index, value, callback), trigger: 'blur' }]">
                  <div style="display: flex; align-items: center; width: 100%">
                    <el-input v-model="item.fieldKey" />
                    <el-button v-if="index > 0" size="small" @click.prevent="removeDomain(item)">删除</el-button>
                  </div>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row style="width: 100%">
              <el-col :span="24">
                <el-button @click="addDomain">再添加一项</el-button>
              </el-col>
            </el-row>
          </template>

          <MOSTY.Assort :title="'附件'" />
          <el-form-item label="附件" style="width: 600px" prop="files">
            <div style="display: flex">
              <MOSTY.Upload isAutoWidth :disabled="['feedback'].includes(props.type)" :limit="500" :nopicer="true"
                :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'xls', 'xlsx', 'wps']" :isImg="false" :ShowfileList="true"
                v-model="formData.files" :showinput="true">
              </MOSTY.Upload>
            </div>
          </el-form-item>

          <el-row style="width: 100%" v-if="!['feedback'].includes(props.type)">
            <el-col :span="12">
              <el-form-item label="下发接收范围" prop="receivingRange">
                <section style="display: flex; align-items: center; width: 100%">
                  <el-radio-group v-model="formData.receivingRange" @change="handleRadioChange" class="ml-4"
                    style="width: 100%">
                    <el-radio :label="item.value" v-for="item in range" :key="item.value">{{ item.title }}</el-radio>
                  </el-radio-group>
                </section>
              </el-form-item>
            </el-col>

            <el-col :span="12" v-if="formData.receivingRange == '04'">
              <el-form-item 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>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>

        <!-- 指定新增人员 start -->
        <addUserTc v-if="isShowAddUser" :isShowFenYe="props.type != 'add'" @choose="addUserChange" />
        <!-- 指定新增人员 end -->
        <section v-if="props.type == 'edit' && oldReceivingRange == '05' && formData.receivingRange == '05'"
          style="margin-bottom: 10px">
          <el-button class="addbtn" type="primary" @click="addUserClick(row)">
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>新增</span>
          </el-button>
        </section>

        <template v-if="isShoswReadTable">
          <section
            style="color: #333; margin-bottom: 20px; padding-left: 10px; display: flex; justify-content: space-between">
            <article>
              下发接收人员数量：<span style="color: rgba(42, 130, 228, 1); font-size: 14px">{{ pageData.pageConfiger.total
                }}</span>人
            </article>
            <section>
              <el-input placeholder="请输入姓名" v-model="pageData.pageConfiger.keywords" clearable
                style="width: 250px"></el-input>
              <el-button @click="queryData" class="ml6">
                <el-icon>
                  <Search />
                </el-icon>查询</el-button>
            </section>
          </section>
          <section>
            <MOSTY.Table :table-columns="tableColumns" :tableData="pageData.tableData"
              :tableloading="pageData.tableloading" style="height: 500px" :actionsW="'120px'">
              <template #state="{ row }">
                <el-tag v-if="row.state == '1'" type="success">已读</el-tag>
                <el-tag v-else-if="row.state == '2'" type="danger">未读</el-tag>
              </template>
              <template #actions="{ row }">
                <el-popconfirm v-if="formData.receivingRange == '05'" confirm-button-text="是" cancel-button-text="否"
                  icon-color="red" title="确定要删除?" @confirm="delRow(row)">
                  <template #reference>
                    <span class="operdel" size="small">
                      <el-icon>
                        <Delete />
                      </el-icon>
                      删除</span>
                  </template>
                </el-popconfirm>
              </template>
            </MOSTY.Table>
          </section>
          <div class="fenye">
            <MOSTY.Pages :pageConfiger="pageData.pageConfiger" @changeNo="handleCurrentChange"
              @changeSize="handleSizeChange" />
          </div>
        </template>
      </template>
      <template #footer>
        <el-button type="primary" @click="submit(ruleFormRef)" v-loading="saveloading"
          v-if="props.type !== 'view'"><el-icon>
            <DocumentChecked />
          </el-icon>
          <span>保存</span>
        </el-button>
        <el-button type="primary" @click="submit(ruleFormRef, 'fb')" v-loading="saveloading"
          v-if="props.type !== 'view'"><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>
        <!-- 选择责任人 -->
        <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :data="memberList" :leaderid="leaderid"
          @choosedUsers="getSonValue"></ChooseUser>
        <!-- <Choosebm :showDdld="showDept" @closezzjg="closezzjg" @listdata="getSonValue" :zzlx="zzlx" /> -->
        <ChooseDept :data="taskList" :showDdld="showDept" :searchType="'01'" @closezzjg="closeJhss" :Isstrictly="true"
          :disabledParent="true" @listdata="getSonValue" :zzlx="zzlx" />
        <!-- 选择下发人 -->
        <ChooseUser v-model="isShowUserTc" :Single="false" :data="memberList" :leaderid="leaderid"
          @choosedUsers="chooseUserOk"></ChooseUser>
      </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 ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue"

import addUserTc from "./detailCom/addUser.vue"
import { feedBackTypeRangeData } from "./../models/detail"

const { proxy } = getCurrentInstance()
// const { D_BZ_TZGGLX } = proxy.$dict("D_BZ_TZGGLX")
//点击下载二维码
const saveloading = ref(false)
const isShowUserTc = ref(false)
const props = defineProps({
  /** type
   * add edit feedback反馈（view）  issue分发,可编辑
   */
  type: {
    default: "",
    type: String
  },
  title: {
    default: "",
    type: String
  },
  id: {
    default: "",
    type: String
  }
})
/** 新增的人员 */
const addUserArr = ref()
/** 是否展示 无分页的新增 */
const isShowAddUser = computed(() => {
  if (formData.value.receivingRange != "05") return false
  if (["add", "issue"].includes(props.type)) return true
  // 编辑模式 之前不是指定人员才显示无分页的人员选择
  if (props.type == "edit" && oldReceivingRange.value != formData.value.receivingRange) return true
  return false
})
/** 是否显示有分页的表格 */
const isShoswReadTable = computed(() => {
  if (["add", "issue"].includes(props.type)) return false
  // 编辑模式 之前和现在选择的是[指定人员]才显示
  // if (formData.value.receivingRange == "05" && oldReceivingRange.value == "05" || oldReceivingRange.value !== "05" && formData.value.receivingRange != "05") return true
  // return false
  if (oldReceivingRange.value == "05") {
    if (formData.value.receivingRange == "05") return true
    return false
  } else {
    if (formData.value.receivingRange != "05") return true
    return false
  }
})
const rules = {
  title: [{ required: true, message: "请输入任务标题", trigger: "blur" }],
  content: [{ required: true, message: "通知任务内容", trigger: "blur" }],
  // files: [{ required: true, message: "上传附件", trigger: "change" }],
  feedBackDate: [{ required: true, message: "请选择反馈日期", trigger: "blur" }],
  receiveDeptName: [{ required: true, message: "请选择指定部门", trigger: "blur" }],
  // time: [{ required: true, message: "请选择动态时间", trigger: "change" }],
  // writer: [{ required: true, message: "撰稿人", trigger: "blur" }],
  receivingRange: [{ required: true, message: "请选择下发范围", trigger: "change" }]
}
const formData = ref({
  type: "01",
  receivingRange: "01",
  feedBackType: "01",
  values: [
    { fieldSort: 1, fieldKey: "" },
    { fieldSort: 2, fieldKey: "" },
    { fieldSort: 3, fieldKey: "" }
  ]
})
const editorConfig = {
  serverUrl: "",
  UEDITOR_HOME_URL: "/UEditorPlus/",
  readonly: false
}
const pageData = reactive({
  tableColumns: [
    {
      title: "接收人员单位",
      prop: "orgName"
    },
    {
      title: "接收人员部门",
      prop: "deptName"
    },
    {
      title: "接收人员姓名",
      prop: "userName"
    },
    {
      title: "状态",
      prop: "state",
      slot: true
    },
    {
      title: "操作",
      prop: "actions",
      width: "120px",
      slot: true
    }
  ],
  tableData: [],
  pageConfiger: {
    pageSize: 10,
    pageCurrent: 1,
    total: 0
  },
  tableloading: false
})
const tableColumns = computed(() => {
  let arr = pageData.tableColumns.filter(item => {
    if (item.prop == "state") return props.type != "add"
    if (item.prop == "actions") return oldReceivingRange.value == "05" && formData.value.receivingRange == "05" && props.type == "edit"
    return true
  })
  return arr
})
const range = ref([
  { title: "各直属部门安全部门", value: "01" },
  { title: "全省各级安全部门成员", value: "02" },
  { title: "全体安全员", value: "03" },
  { title: "指定部门", value: "04" },
  { title: "指定人员", value: "05" },
  { title: "全省人员", value: "06" }
])
const feedBackTypeRange = ref(JSON.parse(JSON.stringify(feedBackTypeRangeData)))
const zzlx = ref(null)

const showDept = ref(false) //选择部门

const emit = defineEmits("close")
const ruleFormRef = ref()
const bigBox = ref()
const leaderid = ref("")
const singleShow = ref(false)
const chooseUserVisible = ref(false)
// const isShowUserTc = ref(false)
const memberList = ref([]) //成员选择的id回显
const taskList = ref([])
const width = ref(null)
/** 旧 下发接收范围 */
const oldReceivingRange = ref()

// 添加数据项
const addDomain = () => {
  formData.value.values.push({
    fieldSort: formData.value.values[formData.value.values.length - 1] + 1,
    fieldKey: ""
  })
}
//删除数据项
const removeDomain = item => {
  const index = formData.value.values.indexOf(item)
  if (index !== -1) {
    formData.value.values.splice(index, 1)
  }
}

// 获取下发范围列表
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 {
  }
}

//监听富文本
watch(
  () => formData.MarkdownEdit,
  val => {
    if (val) {
      formData.MarkdownEdit = val
    }
  }
)
onMounted(() => {
  nextTick(() => {
    width.value = bigBox.value.offsetWidth - 215
  })
  getRangeList()
  // queryData()
  if (props.id) {
    queryDetail()
    // getApi({ id: props.id }, "/mosty-jcgl/noticeController/lookNoticeInfo")
  }
  if (["feedback"].includes(props.type)) {
    editorConfig.readonly = true
  }
})
const addUserClick = () => {
  isShowUserTc.value = true
}
const delRow = row => {
  postApi([row.id], "/mosty-jcgl/noticeUserController/delNoticeUserInfo").then(ref => {
    ElMessage.success("删除人员成功")
    queryData()
  })
}
//页码发生变化
const handleCurrentChange = val => {
  pageData.pageConfiger.pageCurrent = val
  queryData()
}
//查询条数发生变化
const handleSizeChange = val => {
  pageData.pageConfiger.pageSize = val
  queryData()
}
// 选择范围
const handleRadioChange = val => {
  formData.value.receivingRange = val
  formData.value.receiveDeptName = ""
  formData.value.receiveDeptId = ""
  addUserArr.value = []
}
// 查询子表单
const queryData = () => {
  pageData.tableloading = true
  postApi({ noticeId: props.id, ...pageData.pageConfiger }, "/mosty-jcgl/noticeController/queryNoticeUserInfo").then(res => {
    pageData.tableData = res.records
    pageData.pageConfiger.total = res.total
    pageData.tableloading = false
  })
}
// 查询详情
const queryDetail = () => {
  getApi({ id: props.id }, "/mosty-jcgl/taskController/selectOne").then(res => {
    if (props.type === "issue") {
      formData.value.title = res.title
      formData.value.content = res.content
      formData.value.feedBackType = res.feedBackType
      formData.value.feedBackDate = res.feedBackDate
      formData.value.files = res.files
      formData.value.receivingRange = ""
      formData.value.receiveDeptId = ""
      formData.value.receiveDeptName = ""
      formData.value.receiveDeptIds = ""
      formData.value.receiveDeptNames = ""
      addUserArr.value = []
      pageData.tableData = []
      pageData.pageConfiger.total = 0
    } else {
      // formData.value = Object.assign(formData.value, res)
      formData.value = { ...formData.value, ...res, receiveDeptId: res.receiveDeptIds, receiveDeptName: res.receiveDeptNames }
    }

    formData.value.values = (res?.dataValue && JSON.parse(res?.dataValue)) || []
    oldReceivingRange.value = formData.value.receivingRange
    addUserArr.value = []
  })
}
// 生效时间只能选当天及之前的
const disabledDate = time => {
  return time.getTime() < Date.now()
}
/** 转成数组 */
const toArr = val => {
  if (typeof val === "string") return val ? val.split(",") : []
  if (Array.isArray(val)) return val.map(item => item)
  return []
}

//选择部门
const ChooesDdld = val => {
  zzlx.value = val
  console.log("taskList.value: ", taskList.value)
  if (val == "01") {
    showDept.value = true
    // taskList.value = toArr(formData.value.receiveDeptId)
  } else {
    leaderid.value = formData.value.responsibilityperson
    singleShow.value = true
    chooseUserVisible.value = true
  }
}
// 关闭单位部门弹框
const closeJhss = () => {
  taskList.value = []
  showDept.value = false
}
// 关闭弹框
const handleClose = () => {
  if (props.type !== "view") {
    proxy.$modal
      .confirm("离开会丢失页面中修改的内容，确认离开吗？")
      .then(() => {
        emit("close")
      })
      .catch(() => {
        // catch error
      })
  } else {
    emit("close")
  }
}
//关闭选择人员弹窗
const closezzjg = val => {
  showDept.value = val
}
const getSonValue = value => {
  if (zzlx.value == "01") {
    formData.value.receiveDeptName = []
    formData.value.receiveDeptId = []
    value.forEach(item => {
      formData.value.receiveDeptName.push(item.orgName)
      formData.value.receiveDeptId.push(item.id)
    })
    formData.value.receiveDeptName.toString()
    formData.value.receiveDeptId.toString()
    formData.value.receivingRange = "04"
    // formData.value.receivingRange =
  } else if (zzlx.value == "04") {
    formData.value.writer = value[0].userName
    formData.value.writerId = value[0].id
  }
}
const chooseUserOk = val => {
  val = Array.isArray(val) ? val : []
  // const ids = val.map(item => item.id)
  console.log("============>0", val)
  pageData.tableData = val
  pageData.pageConfiger.total = val.length
  // postApi({ id: formData.value.id, userIds: ids }, "/mosty-jcgl/noticeUserController/addNoticeUserInfo").then(res => {
  //   ElMessage.success("新增人员成功")
  //   queryData()
  // })
}

//
const validate = (_index, value, callback) => {
  if (value === "") {
    callback(new Error("请输入"))
  } else {
    const filterLength = formData.value.values.filter(t => t.fieldKey === value)
    if (filterLength.length > 1) {
      callback(new Error("请输入不同的数据项内容"))
      return
    }
    callback()
  }
}
// 保存
const submit = async (ruleFormRef, _type) => {
  saveloading.value = true
  if (!ruleFormRef) return
  await ruleFormRef.validate(valid => {
    if (valid) {
      // let _url = props.id ? "editNoticeInfo" : "saveNoticeInfo"
      let _url = _type ? "issueTaskInfo" : props.id && props.type === "edit" ? "editTaskInfo" : "saveTaskInfo"
      if (props.id) {
        formData.value.id = props.id
      }
      if (props.type === "issue") {
        formData.value.id = ""
      }
      if (Array.isArray(formData.value.receiveDeptId)) {
        formData.value.receiveDeptIds = formData.value.receiveDeptId.toString()
      }
      if (Array.isArray(formData.value.receiveDeptName)) {
        formData.value.receiveDeptNames = formData.value.receiveDeptName.toString()
      }
      if (Array.isArray(formData.value.files)) {
        formData.value.files = formData.value.files.toString()
      }
      const params = { ...formData.value }
      if (isShowAddUser.value) {
        params.issuedUserIds = addUserArr.value.map(t => t.id).join(",")
        params.issuedUserNames = addUserArr.value.map(t => t.userName).join(",")
      }
      // console.log("isShowAddUser.value: ", isShowAddUser.value)
      console.log(params)
      postApi(params, "/mosty-jcgl/taskController/" + _url)
        .then(() => {
          ElMessage.success(_type ? "发布成功" : props.id && props.type === "edit" ? "修改成功" : "保存成功")
          emit("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 {
  // width: 1525px;
  margin: auto;
  padding: 10px;
  margin-top: 10px;
  flex-wrap: wrap;
  justify-content: start;
  // padding: 10px 56px !important;
}

::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;
}
</style>
