<template>
  <div>
    <div class="bigBox">
      <MOSTY.FromPage :title="props.title" @closeDialog="CloseEvent">
        <template #content>
          <MOSTY.Assort :title="'基础信息'" />
          <div class='fromboxs'>
            <el-form ref="ruleFormRef" :model="formData" :rules="rules" :disabled="!props.saveBtnShow"
              label-width="120px" status-icon label-position="right">
              <el-form-item label="名称:" prop="manualname" style="width: 45%">
                <el-input v-model="formData.manualname" maxlength="50" autosize type="textarea" show-word-limit
                  placeholder="不能超过50个字" style="width: 100%"></el-input>
              </el-form-item>
              <el-form-item label="类型:" prop="type" style="width: 45%">
                <MOSTY.DictRidioAndSelect :dictData="props.zdlist.D_BZ_WHSCLX" v-model="formData.type"
                  selectType="select" :disabled="false" style="width: 100%" />
              </el-form-item>
              <el-form-item label="发布时间:" prop="publishtime" style="width: 45%">
                <el-date-picker v-model="formData.publishtime" style="width: 100%" type="date" format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD" />
              </el-form-item>
              <el-form-item label="主要内容:" prop="content" style="width: 100%">
                <el-input v-model="formData.content" :rows="6" maxlength="500" type="textarea" show-word-limit
                  placeholder="不能超过500个字" />
              </el-form-item>
              <el-form-item label="附件:" style="width: 100%">
                <MOSTY.Upload :widthNumber="884" :limit="5" :nopicer="true" :isImg="false" :ShowfileList="true"
                  :isVideosp="props.category == '01' ? false : true" v-model="formData.files" :showinput="true"
                  :delrow="delrow" :disabled="!props.saveBtnShow"
                  :placeholder="props.category == '01' ? '请上传pdf,ofd,wps' : '请上传视频格式文件'"
                  :gsgfList="props.category == '01' ? ['pdf', 'ofd', 'wps'] : ['']" @filehandleChange="changeFile">
                </MOSTY.Upload>
                <div style="margin-left:20%;color:red;" v-if="props.category == '02'"> <span> (仅支持视频格式文件上传)</span></div>
              </el-form-item>
            </el-form>

          </div>
          <MOSTY.Assort :title="'评论'" v-if="!props.saveBtnShow" />
          <div v-if="!props.saveBtnShow" class='fromboxs'>

            <div class="message_box">

              <div class="message">
                <ul v-if="messageList && messageList.length > 0">
                  <li v-for="(item, index) in messageList" :key="index">
                    <div>
                      <div class="userUnit">{{ item.orgname }}（{{ item.deptname }}）</div>
                      <div class="username">
                        <span class="black">评论人：<span class="blue">{{ item.username }}</span></span>
                        <span class="black">评论时间：{{ item.addtime }}</span>
                      </div>
                    </div>
                    <div style="color: gray;line-height: 20px;">{{ item.content }}</div>
                    <div style="margin-top: 10px;" v-if="item.imgArray && item.imgArray.length > 0">
                      <img :src="it.url" v-for="it in item.imgArray" @click="handlePictureCardPreview(it)" :key="it.id">
                    </div>
                    <div class="mt10" v-if="item.fileArray && item.fileArray.length > 0">
                      <span v-for="(it, i) in item.fileArray" :key="i" class="mr10">
                        <span style="color: gray;">附件{{ i + 1 }}:</span>
                        <span class="ckxq textlin" @click="clickFileList(it)" target="_blank">{{ it.originalName
                          }}&ensp;</span>
                        <span class="ckxq" @click="doPreview(it)">【预览】</span>
                      </span>
                    </div>
                    <div v-if="item.userid == USERID" style="display: flex;justify-content: end;">
                      <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
                        @confirm="handledelete(item)">
                        <template #reference>
                          <el-button size="small"><el-icon>
                              <Delete />
                            </el-icon>删除</el-button>
                        </template>
                      </el-popconfirm>
                    </div>
                  </li>
                </ul>
                <div v-else
                  style="width: 100%;height: 100%;color: gray;display: flex;align-items: center;justify-content: center;font-size: 16px;">
                  暂无评论，发布一条试试吧！
                </div>
              </div>
              <div class="fenye">
                <MOSTY.Pages :pageConfiger="pageConfiger" @changeSize="handleSizeChange"
                  @changeNo="handleCurrentChange" />

              </div>
            </div>
          </div>

        </template>
        <template #footer>


          <el-button type="primary" @click="save(ruleFormRef)" :loading="loading" v-if="props.saveBtnShow">
            <el-icon>
              <DocumentChecked />
            </el-icon>
            <span>保存</span>
          </el-button>
          <el-button type="primary" @click="openSend(formData.id)" v-if="!props.saveBtnShow">
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>评论</span>
          </el-button>
          <el-button type="primary" @click="CloseEvent">
            <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span>
          </el-button>
        </template>
      </MOSTY.FromPage>
      <!-- 预览 -->
      <el-dialog v-model="flyldialog" :show-close="false" top="10px" bottom="10px">
        <div style="height: 84vh; text-align: center">
          <Kkfile :files="fileid" @changedialog="changedialog" />
        </div>
      </el-dialog>
      <!-- 放大 -->
      <el-dialog v-model="dialogVisible" :show-close="false" top="10px" bottom="10px">
        <div style="height: 80vh; text-align: center">
          <el-image style="width: 47vw; height: 75vh" :src="dialogImageUrl" fit="scale-down" />
          <el-button type="primary" @click="dialogVisible = false">
            <el-icon>
              <Close />
            </el-icon>
            <span>关闭</span>
          </el-button>
        </div>
      </el-dialog>
      <!--评论 -->
      <div v-if="DiaShow" class="dialod">
        <el-dialog :title="'评论内容'" v-model="DiaShow" stripe width="800px" top="10%" :before-close="handleClose">
          <div class="config">
            <el-form ref="ruleFormRefs" :model="ruleForm" :rules="rules" label-width="135px" style="display: block;"
              :inline="true">
              <el-form-item label="评论内容" style="width: 77%;">
                <el-input v-model="ruleForm.content" :rows="5" type="textarea" style="width: 100%;" />
              </el-form-item>
              <el-form-item label="附件：">
                <MOSTY.Upload v-model="ruleForm.files" :delrow="delrow" :widthNumber="455" :isEdit="fileEdit"
                  :ShowfileList="true" :showinput="true" :limit="5" :nopicer="true" :isImg="false" />
              </el-form-item>
            </el-form>
          </div>
          <template #footer>
            <span class="dialog-footer">

              <el-button type="primary" @click="handleSave(ruleFormRefs)" :loading="saveLoading">
                <el-icon>
                  <DocumentChecked />
                </el-icon>
                <span>保存</span>
              </el-button>
              <el-button @click="handleClose" type="primary">
                <el-icon>
                  <DocumentDelete />
                </el-icon>
                <span>关闭</span>
              </el-button>
            </span>
          </template>
        </el-dialog>
      </div>
    </div>

  </div>
</template>

<script setup>
// 引入
import { reactive, onMounted, ref, defineProps, watch, getCurrentInstance } from "vue";
import { ElMessage } from "element-plus";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import Kkfile from "@/components/MyComponents/kkfile/index.vue";
import { createAndClickLink } from "@/utils/tools.js";
import * as MOSTY from "@/components/MyComponents/index";
import { getItem } from "@/utils/storage";
const emits = defineEmits(["close"]);
const { proxy } = getCurrentInstance();
const props = defineProps({
  saveBtnShow: {
    default: true,
    type: Boolean
  },
  zdlist: Object,
  rwid: String,
  title: String,
  RowId: String,
  category: String,
});
// 数据
const USERID = getItem("USERID");
const dialogVisible = ref(false);
const fileid = ref('')
const dialogImageUrl = ref("");
const delrow = ref({});
const ruleFormRef = ref();
const fjList = ref([])
const ruleFormRefs = ref();
const DiaShow = ref(false)
const saveLoading = ref(false)
const ruleForm = ref({})
const formData = ref({});
// 图片后缀列表
const imgSuffix = ref(['.bmp', '.jpg', '.png', '.tif', '.gif', '.pcx', '.apng', '.webp'])

const rules = reactive({
  manualname: [
    { required: true, message: "手册名称不能为空", trigger: "blur" }
  ],
  type: [
    { required: true, message: "类型不能为空", trigger: "blur" }
  ],
  publishtime: [{ required: true, message: "发布时间不能为空", trigger: "blur" }],
  content: [
    { required: true, message: "主要内容不能为空", trigger: "blur" }
  ],
});
const messageList = ref([])
const listQuery = ref(
  {
    pageSize: 20,
    pageCurrent: 1,
  }
)
const pageConfiger = reactive({
  pageSize: 20,
  pageCurrent: 1,
  total: 0
})
const flyldialog = ref(false)
// 预览
function doPreview(item) {
  if (item) {
    fileid.value = item.id;
    flyldialog.value = true
  } else {
    ElMessage.warning(`请先上传文件`);
  }
}
// 关闭预览
function changedialog() {
  flyldialog.value = false
  fileid.value = ''
}
//关闭综合配置表
const CloseEvent = () => {
  if (props.saveBtnShow) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        // 关闭上一次的表单校验
        ruleFormRef.value.clearValidate();
        emits("close");
      })
      .catch(() => {
        // catch error
      })
  } else {
    // 关闭上一次的表单校验
    ruleFormRef.value.clearValidate();
    emits("close");
  }


};

onMounted(() => {

});
watch(
  () => props.RowId,
  (val) => {
    if (val) {
      getxqData(val)
    }

  },
  { deep: true, immediate: true }
);
//获取详情
function getxqData(id) {
  getApi({ id }, `/mosty-jcgl/cultureManual/getInfo`).then(
    (res) => {
      if (res) {
        formData.value = res;
        if (!props.saveBtnShow) {
          getList()
        }
      }
    }
  );
}
const loading = ref(false); //新增保存按钮截流
const save = async (ruleFormRef) => {
  if (!ruleFormRef) return;
  await ruleFormRef.validate((valid) => {
    if (valid) {
      loading.value = true;
      formData.value.files = formData.value.files ? formData.value.files.toString() : null;
      formData.value.category = props.category;
      if (formData.value.id) {
        postApi(formData.value, "/mosty-jcgl/cultureManual/edit")
          .then((res) => {
            loading.value = false;
            ElMessage.success("修改成功");
            emits("close");
          })
      } else {
        postApi(formData.value, "/mosty-jcgl/cultureManual/add")
          .then((res) => {
            loading.value = false;
            ElMessage.success("新增成功");
            emits("close");
          })
      }
    } else {
      ElMessage.error("请输入必填项!");
    }
  });
};
//获取文化手册的评论
function getList() {
  listQuery.value.ywid = formData.value.id
  listQuery.value.ywlx = formData.value.category
  getApi(listQuery.value, '/mosty-jcgl/comment/getPageList').then(res => {
    if (res.records) {
      pageConfiger.total = res.total;

      res.records.forEach(it => {
        let fileArray = []
        let imgArray = []
        it.fileList.forEach(ele => {
          if (imgSuffix.value.indexOf(ele.suffix.toLowerCase()) !== -1) {
            ele.isImg = true
            fjList.value.push(ele)
            imgArray.push(ele)
          } else {
            ele.isImg = false
            fjList.value.push(ele)
            fileArray.push(ele)
          }
        });
        it.fileArray = fileArray
        it.imgArray = imgArray
      })
      messageList.value = res.records
    }


  })
}
const handleSizeChange = (currentSize) => {
  listQuery.pageSize = currentSize;
  pageConfiger.pageSize = currentSize;
  getListData();
};
const handleCurrentChange = (currentPage) => {
  listQuery.pageCurrent = currentPage;
  pageConfiger.pageCurrent = currentPage;
  getListData();
};
// 图片放大
const handlePictureCardPreview = (file) => {
  dialogImageUrl.value = file.url;
  dialogVisible.value = true;
};
// 下载附件
const clickFileList = (file) => {
  createAndClickLink(file.url, file.name);
};
// 关闭评论弹窗
function handleClose() {
  proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
    .then(() => {
      DiaShow.value = false
      ruleFormRefs.value.clearValidate();
      ruleFormRefs.value.resetFields()
      ruleForm.value = {}
      getList()
    })
    .catch(() => {
      // catch error
    })

}
// 打开评论弹窗
function openSend() {
  DiaShow.value = true
}
// 接收外层新增保存
const handleSave = async (ruleFormRefs) => {
  if (!ruleFormRefs) return;
  await ruleFormRefs.validate((valid) => {
    if (valid) {
      saveLoading.value = true;
      ruleForm.value.files = ruleForm.value.files ? ruleForm.value.files.toString() : null;
      ruleForm.value.ywid = formData.value.id
      ruleForm.value.ywlx = formData.value.category
      postApi(ruleForm.value, "/mosty-jcgl/comment/add").then(() => {
        saveLoading.value = false;
        ElMessage.success("评论发送成功");
        DiaShow.value = false
        ruleFormRefs.value.clearValidate();
        ruleFormRefs.value.resetFields()
        ruleForm.value = {}
        getList()
      }).catch(() => {
        saveLoading.value = false;
      })
    } else {
      ElMessage.error("请输入必填项!");
    }
  });
};
//删除评论
function handledelete(val) {
  postApi({}, `/mosty-jcgl/comment/del/${val.id}`).then(res => {
    ElMessage.success("评论删除成功");
    getList()

  })
}
</script>

<style lang="scss" scoped>
.ckxq {
  color: var(--el-color-primary);
  text-decoration: underline;
  cursor: pointer;
}

.bigBox {
  display: black;

}

.Box {
  margin: 10px auto;
  // width: calc(100% - 200px);
  width: 65%;
  color: black;
  font-size: 20px;
}

.first {
  display: flex;
  align-items: center;

  .el-form-item {
    width: 100%;
    display: flex;
    align-items: center;

    .el-input {
      width: 98%;
    }
  }
}

.el-form {
  width: 100%;
  align-items: center;
  display: flex;
  justify-content: space-between;
  flex-wrap: wrap;
}

.ld_box {
  display: flex;
  margin-right: 30px;
}

.el-collapse {
  padding: 10px;
}

.fromboxs {
  display: flex;
  justify-content: center;
  width: 1000px;
  margin: 0 auto;
}

.message_box {
  width: 100%;
  // height: calc(100vh - 600px);
  // border-top: 1px solid #e1e1e1;
  overflow: auto;
  padding-bottom: 150px;
  box-sizing: border-box;

  .message {
    overflow-y: auto;
    margin-block-start: 0 !important;

    li {
      padding: 20px 15px;
      border-bottom: 1px solid #e1e1e1;

      .userUnit {
        color: #000;
        font-size: 14px;
        font-weight: 600;
      }

      .username {
        padding: 10px 0;
        display: flex;
        justify-content: space-between;
      }
    }
  }
}

img {
  object-fit: scale-down;
  width: 80px;
  height: 80px;
  margin-right: 10px;
  background: #e0e0e0;
}

.black {
  color: #000;
}
</style>