<template>
  <div class="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="30" placeholder="请输入典型名称"
                  :disabled="props.type == 'view' || props.type == 'approve'" clearable></el-input>
              </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="12">
              <el-form-item label="案例时间" prop="caseTime">
                <el-date-picker v-model="formData.caseTime" style="width: 100%" type="date"
                  :disabled="props.type == 'view' || props.type == 'approve'" value-format="YYYY-MM-DD"
                  placeholder="选择案例日期时间" />
              </el-form-item>
            </el-col>
          </el-row>

          <MOSTY.Assort :title="'案例图片、文件'" />
          <el-form-item label="案例图片" style="width: 100%" prop="titleFile">
            <div style="display: flex">
              <MOSTY.Upload :width="'100%'" :disabled="props.type == 'view' || props.type == 'approve'" :limit="10"
                :nopicer="false" :isImg="true" :ShowfileList="false" v-model="formData.titleFile" :nameshow="true"
                :gsgfList="['jpg', 'png']">
              </MOSTY.Upload>
            </div>
          </el-form-item>
          <el-form-item label="其他文件" style="width: 100%">
            <div style="display: flex">
              <MOSTY.Upload isAutoWidth v-model="formData.otherFile"
                :disabled="props.type == 'view' || props.type == 'approve'" :limit="5"
                placeholder="请上传文件（pdf,ofd,doc,docx,xls,xlsx,wps）" :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'wps']"
                nopicer :isImg="false" ShowfileList showinput>
              </MOSTY.Upload>
            </div>
          </el-form-item>
          <MOSTY.Assort :title="'审批信息'" v-if="type == 'approve' || (type == 'view' && formData.reviewerMsg)" />
          <el-row style="width: 100%" v-if="type == 'approve'">
            <el-col :span="12">
              <el-form-item label="是否通过" style="width: 100%">
                <el-radio-group v-model="formData.state" class="ml-4"
                  :disabled="props.type == 'view' || props.type == 'edit'">
                  <el-radio label="02">通过</el-radio>
                  <el-radio label="03">不通过</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row style="width: 100%" v-if="isShowAuditInput(formData)">
            <el-col :span="24">
              <el-form-item label="审批意见" prop="reviewerMsg">
                <el-input v-if="isShowReviewerMsg()" v-model="formData.reviewerMsg"
                  :disabled="props.type == 'view' || props.type == 'edit'" type="textarea" placeholder="请输入审批反馈意见。"
                  autosize></el-input>
                <el-input v-if="isShowSecondReviewerMsg()" v-model="formData.secondReviewerMsg"
                  :disabled="props.type == 'view' || props.type == 'edit'" type="textarea" placeholder="请输入审批反馈意见"
                  autosize></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </template>
      <template #footer>
        <el-button type="primary" @click="submit(ruleFormRef)" v-loading="saveloading"
          v-if="props.type !== 'view'"><el-icon>
            <DocumentChecked />
          </el-icon>
          <span>{{ type === "approve" ? "提交" : "保存" }}</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" />
      </template>
    </MOSTY.FromPage>
  </div>
</template>

<script setup>
import { watch, ref, getCurrentInstance, defineAsyncComponent, onMounted, computed } from "vue"
import * as MOSTY from "@/components/MyComponents/index"
import Choosebm from "@/components/MyComponents/ChooseDept/index.vue"
import { ElMessage } from "element-plus"
import { getApi, postApi } from "@/api/tobAcco_api.js"
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue"
import { getItem } from "@/utils/storage"
import { timeValidate } from "@/utils/tools.js"
import { filterqx, getLevel } from "../../../../utils/auth.js" // isSgs,isgs,isxgs,isaqbm,isldbz
/** 组织层级 */
const orgLevel = getItem("deptId").orgLevel
const { proxy } = getCurrentInstance()
// const { B_BZ_DTCJ } = proxy.$dict("B_BZ_DTCJ")
//点击下载二维码
const saveloading = ref(false)
const rules = {
  title: [{ required: true, message: "请填写典型案例标题", trigger: "blur" }],
  content: [{ required: true, message: "请填写典型内容", trigger: "blur" }]
}
/**
 * 表单数据对象，包含典型案例相关的各项属性
 *
 * @typedef {Object} FormData
 * @property {string|undefined} id - id
 * @property {string|undefined} state - 当前状态（例如：是否通过审核）
 * @property {string|undefined} secondState - 二次状态（市上报到省时使用）
 * @property {string} title - 典型名称,标题，
 * @property {string} content - 内容，富文本
 * @property {(string | File)[]} titleFile - 动态标题图片
 * @property {(string | File)[]} otherFile - 其他动态文件
 * @property {string} reviewerMsg - 审核意见（县到市的审批流程中使用）
 * @property {string} secondReviewerMsg - 二次审核意见（市上报到省时使用）
 */

/**
 * @type {import('vue').Ref<FormData>}
 */
const formData = ref({
  state: undefined,
  secondState: undefined,
  title: '',
  content: '',
  titleFile: undefined,
  otherFile: undefined,
  reviewerMsg: undefined,
  secondReviewerMsg: undefined,
})
const editorConfig = {
  serverUrl: "",
  UEDITOR_HOME_URL: "/UEditorPlus/",
  readonly: false
}
/** 是否是省账号 */
const isProvinceTrue = computed(() => {
  return filterqx("isSgs") == "1"
})
const zzlx = ref(null)
const props = defineProps({
  type: {
    default: "",
    type: String
  },
  title: {
    default: "",
    type: String
  },
  id: {
    default: "",
    type: String
  },
  currRow: {
    type: Object,
    default: {}
  }
})
const showDept = ref(false) //选择部门
const emit = defineEmits("close")
const ruleFormRef = ref()
const leaderid = ref("")
const singleShow = ref(false)
const chooseUserVisible = ref(false)
const memberList = ref([]) //成员选择的id回显
//监听富文本
watch(
  () => formData.MarkdownEdit,
  val => {
    if (val) {
      formData.MarkdownEdit = val
    }
  }
)

onMounted(() => {
  if (props.id) {
    queryDetail()
    // setDetail(props.currRow)
  }
  if (props.title.includes("新增")) {
    // 自动填充【publisher】和【时间】
    formData.value.time = timeValidate(new Date())
    // formData.value.writer = localStorage.getItem("USERNAME")
    // formData.value.writerId = localStorage.getItem("USERID")
  }
  if (props.type == "view" || props.type == "approve") {
    editorConfig.readonly = true
  }
})

const setDetail = (formObj = {}) => {
  formData.value = Object.assign(formData.value, { ...formObj })
  if (props.type === "approve") {
    formData.value.state = "02" // 默认状态为通过
  }
}
// 查询详情
const queryDetail = () => {
  getApi({ id: props.id }, "/mosty-jcgl/typicalCases/selectOne").then(res => {
    formData.value = Object.assign(formData.value, res)
    if (props.type === "approve") {
      formData.value.state = "02" // 默认状态为通过
      let level = getLevel()
      // if (level == 1) {
      //   formData.value.secondReviewerMsg = "" // 审核清空之前的评论
      // } else if (level == 2) {
      //   formData.value.reviewerMsg = "" // 审核清空之前的评论
      // }
    }
  })
}

//选择部门
const ChooesDdld = val => {
  zzlx.value = val
  if (val == "01") {
    showDept.value = true
  } else {
    leaderid.value = formData.value.userId
    singleShow.value = true
    chooseUserVisible.value = true
  }
}
// 关闭弹框
const handleClose = val => {
  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.deptName = value.orgName
    formData.value.deptId = value.id
    // publisher
  } else if (zzlx.value == "04") {
    formData.value.writer = value[0].userName
    formData.value.writerId = value[0].id
  } else {
    formData.value.userName = value[0].userName
    formData.value.userId = value[0].id
  }
}
/** 县提到市的审核意见 */
const isShowReviewerMsg = () => {
  let level = getLevel()
  if (props.type == 'approve') return level == 2 // 审核模式-市可看
  if (props.type == 'view') return level == 3 // 查看模式-县可看
}
const isShowSecondReviewerMsg = () => {
  let level = getLevel()
  if (props.type == 'approve') return level == 1 // 审核模式-省可看
  if (props.type == 'view') return level == 2 // 查看模式-市可看
}
const isShowAuditInput = () => {
  return isShowReviewerMsg() || isShowSecondReviewerMsg()
}
// 保存
const submit = async ruleFormRef => {
  saveloading.value = true
  if (!ruleFormRef) return

  // return
  await ruleFormRef.validate(valid => {
    if (valid) {
      if (props.type == "approve") {
        let params = {
          id: props.id,
          reviewerMsg: formData.value.reviewerMsg, // 顶部控制显示
          secondReviewerMsg: formData.value.secondReviewerMsg, // 顶部控制显示
          // state: formData.value.state,
          // secondState
        }
        // 省审核是二次审核 (市：20 推上来的)
        if (formData.value.level == '20') {
          params.secondState = formData.value.state
        } else {
          params.state = formData.value.state
        }
        postApi(params, "/mosty-jcgl/typicalCases/examineTypicalCases")
          .then(() => {
            ElMessage.success("审批成功")
            emit("close", true)
          })
          .finally(() => {
            saveloading.value = false
          })
      } else {
        let _url = props.id ? "editSecurityDynamics" : "saveSecurityDynamics"
        if (props.id) {
          formData.value.id = props.id
        }
        formData.value.titleFile = formData.value.titleFile ? formData.value.titleFile.toString() : ""
        formData.value.otherFile = formData.value.otherFile ? formData.value.otherFile.toString() : ""
        const addUrl = "/mosty-jcgl/typicalCases/saveTypicalCases"
        const editUrl = "/mosty-jcgl/typicalCases/editTypicalCases"
        postApi(formData.value, props.id ? editUrl : addUrl)
          .then(() => {
            ElMessage.success(props.id ? "修改成功" : "保存成功")
            emit("close", true)
          })
          .finally(() => {
            saveloading.value = false
          })
      }
    } else {
      saveloading.value = false
    }
  })
}
</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>
