<template>
  <div>
    <div class="bigBox" :style="{ height: bigHeight }">
      <MOSTY.FromPage :title="props.title" @closeDialog="CloseEvent">
        <template #content>
          <MOSTY.Assort :title="'基本信息'" />
          <div class="formboxs">
            <el-form ref="ruleFormRef" :model="formData" :rules="rules" :disabled="!props.saveBtnShow"
              label-width="120px" class="demo-ruleForm" status-icon :inline="true" label-position="right">
              <el-form-item label="活动类别:" prop="type" style="width: 45%">
                <MOSTY.DictRidioAndSelect :dictData="props.zdlist.D_BZ_XCYHDLB" v-model="formData.type"
                  selectType="select" :disabled="false" style="width: 100%" @getselect="getselect" />
              </el-form-item>
              <el-form-item label="活动名称：" style="width: 45%" prop="activitiesname">
                <el-input v-model="formData.activitiesname" maxlength="50" autosize type="textarea" show-word-limit
                  placeholder="不能超过50个字" style="width: 100%" :disabled="formData.type != '4'"></el-input>
              </el-form-item>
              <el-form-item label="学时" prop="hour" style="width: 45%">
                <el-input style="width: 100%" v-model.number="formData.hour" type="Number" />
              </el-form-item>
              <el-form-item label="开始时间" prop="startDate" style="width: 45%">
                <el-date-picker v-model="formData.startDate" type="date" label="开始时间" format="YYYY-MM-DD" clearable
                  value-format="YYYY-MM-DD" placeholder="请选择开始时间" style="width: 100%" :disabled-date="disablednowDate1"
                  @change="formData.endDate = ''" />
              </el-form-item>
              <el-form-item label="结束时间" prop="endDate" style="width: 45%">
                <el-date-picker v-model="formData.endDate" type="date" label="结束时间" value-format="YYYY-MM-DD" clearable
                  format="YYYY-MM-DD" placeholder="请选择结束时间" style="width: 100%" :disabled-date="disabledjsrq" />
              </el-form-item>
              <el-form-item label="活动地点：" style="width: 100%" prop="activitiesaddress">
                <el-input v-model="formData.activitiesaddress" maxlength="50" autosize type="textarea" show-word-limit
                  placeholder="不能超过50个字" style="width: 100%"></el-input>
              </el-form-item>
              <el-form-item label="活动概述：" prop="activitiessummarize" style="width: 100%">
                <el-input v-model="formData.activitiessummarize" placeholder="不能超过400个字" type="textarea" show-word-limit
                  maxlength="400" />
              </el-form-item>
              <el-form-item label="备注：" style="width: 100%">
                <el-input v-model="formData.bz" type="textarea" show-word-limit maxlength="400" />
              </el-form-item>
              <el-form-item label="上传附件：" style="width: 100%">
                <MOSTY.Upload :widthNumber="745" :limit="5" :nopicer="true" :isImg="false" :ShowfileList="true"
                  :placeholder="'请上传pdf,ofd, doc, docx,wps'" :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'wps']"
                  v-model="formData.files" :showinput="true" :delrow="delrow" :disabled="!props.saveBtnShow"
                  @filehandleChange="changeFile" :keys="key"></MOSTY.Upload>
              </el-form-item>
              <el-form-item label="上传图片：" style="width: 100%">
                <MOSTY.Upload width="150px" :limit="5" :nopicer="false" :isImg="true" :ShowfileList="false"
                  v-model="formData.picture" @filehandleChange="changeFiles" :disabled="!props.saveBtnShow">
                </MOSTY.Upload>
              </el-form-item>
              <MOSTY.Assort :title="'参与人员'" />
              <section class="eltab4">
                <el-button @click="ChooesDdld('01')" style="margin: 10px;">选择人员</el-button>
                <MOSTY.Table :table-columns="tableColumn" :tableData="formData.idList" :isSelect="false" :isSort="true"
                  @SortChange="SortChange" style="width: 100%;">
                  <template #level="{ row }">
                    <dict-tag :options="D_BZ_LWJB" :value="row.level" :tag="false" />
                  </template>
                  <template #actions="{ row }">
                    <span class="operesee" size="small" @click="showImage(row.imgs)" v-if="row.imgs">
                      <el-icon>
                        <Compass />
                      </el-icon>查看图片</span>
                    <el-popconfirm v-if="saveBtnShow" confirm-button-text="是" cancel-button-text="否" icon-color="red"
                      title="确定要删除?" @confirm="handledelete(row)">
                      <template #reference>
                        <span class="operdel" size="small">
                          <el-icon>
                            <Delete />
                          </el-icon>删除</span>
                      </template>
                    </el-popconfirm>
                    <span v-if="!row.imgs && !saveBtnShow">--</span>
                  </template>
                </MOSTY.Table>
                <div class="fenye" v-if="formData.id">
                  <MOSTY.Pages :pageConfiger="pageConfiger" @changeSize="handleSizeChange"
                    @changeNo="handleCurrentChange" />

                </div>
              </section>
            </el-form>
            <div style="color: black;width: 200px" v-if="formData.id">
              <div class='ertimg'>
                <MOSTY.ErwmImg :url="qrcodepxImg(formData.id, 'xcyhd', formData.activitiesname, newData)"
                  :filename='formData.activitiesname' />
              </div>
            </div>
          </div>
        </template>
        <template #footer>

          <el-button type="primary" @click="save(ruleFormRef)" v-if="saveBtnShow">
            <el-icon>
              <DocumentChecked />
            </el-icon>
            <span>保存</span>
          </el-button>
          <el-button type="primary" @click="CloseEvent">
            <el-icon>
              <DocumentDelete />
            </el-icon>
            <span>关闭</span>
          </el-button>
        </template>
      </MOSTY.FromPage>
    </div>
    <!-- 选择参与人员 -->
    <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :data="memberList" :leaderid="leaderid"
      @choosedUsers="getSonValue"></ChooseUser>

    <!-- element-plus内部组件 -->
    <div class="demo-image__preview">
      <el-image-viewer @close="() => { showViewer = false }" v-if="showViewer" :url-list="imgList" />
    </div>
  </div>
</template>

<script setup>
// 引入
import { reactive, onMounted, ref, defineProps, getCurrentInstance } from "vue";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import { qrcodepxImg } from "@/utils/tools.js";
import { ElMessage } from "element-plus";
import * as rule from "@/utils/rules.js";
import { dateFormat } from "@/utils/tools.js"
import { disablednowDate1 } from '@/utils/tools.js'
import { getItem } from "@/utils/storage";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { getFileUrl } from "@/utils/getFile.js";
const imgList = ref([])
const showViewer = ref(false)
const { proxy } = getCurrentInstance();
import * as MOSTY from "@/components/MyComponents/index";
const emits = defineEmits(["close"]);
const deptId = getItem("deptId").ssbmid;
const props = defineProps({
  saveBtnShow: {
    default: true,
    type: Boolean
  },
  zdlist: Object,
  title: String,
  rowId: String,
});
const newData = ref(dateFormat({ type: 'day' }))
const tableColumn = ref([
  {
    title: "所属单位",
    prop: "orgname",
    sortable: true
  },
  {
    title: "所属部门",
    prop: "deptname",
    sortable: true
  },
  {
    title: "人员姓名",
    prop: "username",
    sortable: true
  },
  {
    title: "签到次数",
    prop: "count",
    sortable: true
  },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
const pageConfiger = reactive({
  pageSize: 10,
  pageCurrent: 1,
  total: 0
})
const chooseUserVisible = ref(false);
const singleShow = ref(true); //单选多选
const leaderid = ref("");
const delrow = ref(null);
const key = ref(0)
const ruleFormRef = ref();
const memberList = ref([]);
const bigHeight = ref(); //整个高度
const formData = ref({})
const rules = reactive({
  type: [{ required: true, message: "请选择活动类别", trigger: "change" }],
  activitiesname: [{ required: true, message: "请输入活动名称", trigger: "change" }],
  activitiesaddress: [{ required: true, message: "请输入活动地点", trigger: "change" }],
  participants: [{ required: true, message: "请选择参与人员", trigger: "change" }],
  startDate: [{ required: true, message: "请选择开始日期", trigger: "change" }],
  endDate: [{ required: true, message: "请选择结束日期", trigger: "change" }],
  activitiessummarize: [{ required: true, message: "请输入活动概述", trigger: "change" }],
  ...rule.numbernineRule({ validator: true, require: true, iszs: true, firstNum: 8, lastNum: 1 }, "hour"),
});
const CloseEvent = () => {
  if (props.saveBtnShow) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        // 关闭上一次的表单校验
        ruleFormRef.value.clearValidate();
        emits("close");
      })
      .catch(() => {
        // catch error
      })
  } else {
    // 关闭上一次的表单校验
    ruleFormRef.value.clearValidate();
    emits("close");
  }

};
onMounted(() => {
  bigHeightFn();
  if (props.rowId) {
    getxqData(props.rowId)
    getrylist(props.rowId)
  }
});
// 查看大图
async function showImage(imgs) {
  let arr = imgs.split(',')
  for (let i = 0; i < arr.length; i++) {
    imgList.value.push(await this.getFileUrl(arr[i]))
  }
  showViewer.value = true
}
function getselect(val) {
  if (val.value != '4') {
    formData.value.activitiesname = val.label
  } else {
    formData.value.activitiesname = ''
  }

}
function disabledjsrq(time) {
  return time.getTime() + 24 * 60 * 60 * 1000 < new Date(formData.value.startDate).getTime()
}
//获取详情
function getxqData(id) {
  getApi({ id }, `/mosty-jcgl/publicityActivities/getInfo`
  ).then((res) => {
    if (res) {
      formData.value = res;
    }
  });
}
//分页
const handleSizeChange = (currentSize) => {
  pageConfiger.pageSize = currentSize;
  getrylist(formData.value.id);
};
const handleCurrentChange = (currentPage) => {
  pageConfiger.pageCurrent = currentPage;
  getrylist(formData.value.id);
};
//查询参与人员列表
function getrylist(id) {
  let prams = {
    pageCurrent: pageConfiger.pageCurrent,
    pageSize: pageConfiger.pageSize,
    activityId: id,
  }
  getApi(prams, '/mosty-jcgl/publicityActivities/getSignInPage').then(res => {
    pageConfiger.total = res.total;
    formData.value.idList = res.records;
  })
}
// 方法
const bigHeightFn = () => {
  bigHeight.value = window.innerHeight - 57 - 41 + "px";
};
//删除参加人员
function handledelete(val) {
  if (formData.value.id) {
    postApi({}, `/mosty-jcgl/publicityActivities/delSignIn/${val.id}`).then(res => {
      ElMessage.success("人员删除成功");
      getrylist(formData.value.id)
    })
  } else {
    formData.value.idList = formData.value.idList.filter((item) => {
      return item.userid !== val.userid;
    });
  }

}
const zzlx = ref(null);
const changeFiles = () => { };
// 新的文件上传返回
const changeFile = (data) => {
  key.value++
};

function ChooesDdld(val) {
  zzlx.value = val;
  if (formData.value.idList && formData.value.idList.length > 0) {
    memberList.value = formData.value.idList.map((item) => {
      return item.userid;
    });
  }
  chooseUserVisible.value = true;
  singleShow.value = false;
}
const getSonValue = (value) => {
  if (formData.value.id) {
    let obj = {
      id: formData.value.id,
      idList: []
    }
    obj.idList = value.map((item) => {
      return { userid: item.id, username: item.userName, deptname: item.deptName, orgname: item.ssdwmc };
    });

    addrylist(obj)
  } else {
    formData.value.idList = value.map((item) => {
      return { userid: item.id, username: item.userName, deptname: item.deptName, orgname: item.ssdwmc };
    });
    memberList.value = value.map((item) => {
      return item.id;
    });
  }
};
//新增人员数据
function addrylist(obj) {
  postApi(obj, '/mosty-jcgl/publicityActivities/addSignIn').then(res => {
    ElMessage.success("人员新增成功");
    getrylist(formData.value.id)
  })
}
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.picture = formData.value.picture ? formData.value.picture.toString() : null;
      if (formData.value.id) {
        postApi(
          formData.value,
          "/mosty-jcgl/publicityActivities/edit"
        )
          .then((res) => {
            ElMessage.success("修改成功");
            emits("close");
          }).finally(() => {
            loading.value = false;
          })

      } else {
        postApi(
          formData.value,
          "/mosty-jcgl/publicityActivities/add"
        )
          .then((res) => {
            ElMessage.success("新增成功");
            emits("close");
          }).finally(() => {
            loading.value = false;
          })
      }

    } else {
      ElMessage.error("请输入必填项!");
    }
  });
};

</script>

<style lang="scss" scoped>
.eltab4 {
  height: 40vh;
  width: 100%;
}

.bigBox {
  display: block;

  .title {
    height: 60px;
    line-height: 60px;
    font-size: 18px;
    color: #0f3916;
  }

  .left {
    width: 300px;
    // height: 100%;
    display: flex;
    flex-direction: column;
    border: 1px solid var(--el-color-primary);

    .treeBox {
      margin-top: 15px;
    }
  }

  .right {
    width: 100%;
    padding: 10px;
    box-sizing: border-box;
  }

  .btnBox {
    display: flex;
  }
}

.Box {
  border: 1px solid var(--el-color-primary);
  margin: 10px auto;
  width: 1000px;
  color: black;
  font-size: 20px;
}

.formboxs {
  display: flex;
  justify-content: center;
  width: 895px;
  margin: 10px auto;
}

.first {
  display: flex;
  align-items: center;
  width: 90%;

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

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

::v-deep .el-form-item__content {
  align-items: start !important;
}

.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;
  height: 73vh;
  overflow: auto;
}

::v-deep .el-collapse-item__content {
  padding: 20px;
}

.ertimg {
  width: 200px;
  height: 176px;
  overflow: hidden;
}

.labl {
  text-align: center;
  font-size: 14px;
  color: #958f8f;
}
</style>