<template>
  <div>
    <MOSTY.PageTree :searchType="'03'" @getDeptId="getdeptId">
      <template #serach>
        <div class="wyh" ref="getHeight">
          <div v-if="showBanner && imgList && imgList.length" style="position: relative">
            <el-carousel indicator-position="none" @change="changeBanner" :motion-blur="true">
              <el-carousel-item v-for="(item) in imgList" :key="item">
                <div style="position: relative;" @click="seeUserHander(item)">
                  <img :src="item.img" alt="">
                  <div style="color: black;position: absolute;bottom: 20px;padding-left: 20px;">{{ item.activityname }}
                  </div>
                </div>
              </el-carousel-item>
            </el-carousel>
            <el-button type="primary" @click="showGhcy"
              style="position: absolute;top: 15px;right: 20px;">工会成员</el-button>
          </div>
          <div v-if="!showBanner">
            <div class="head">
              <div class="title">工会成员</div>
              <div>
                <!-- v-if="filterqx('isaqbm') == '1' && addshow" -->
                <el-button type="primary" @click="submit(ruleFormRef)">保存</el-button>
                <el-button type="primary" @click="showGhcy">返回</el-button>
              </div>
            </div>
            <!-- 内容 -->
            <div class="form">
              <!--  :disabled="filterqx('isaqbm') != '1' || !addshow" -->
              <el-form ref="ruleFormRef" :model="fromObj" :rules="rules" label-width="155px" class="from_box">
                <el-form-item label="所属单位:" prop="orgname">
                  <el-input v-model="fromObj.orgname" style="width: 726px" disabled>
                  </el-input>
                </el-form-item>
                <el-form-item label="所属部门：" prop="deptname">
                  <el-input v-model="fromObj.deptname" style="width: 726px" disabled>
                    <template #append>
                      <el-button class='cursor' @click="ChooesDdld('01')">选择</el-button>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item label="工会成员：" prop="username">
                  <el-input v-model="fromObj.username" style="width: 726px" disabled>
                    <template #append>
                      <el-button class='cursor' @click="ChooesDdld('02')">选择</el-button>
                    </template>
                  </el-input>
                </el-form-item>
                <el-form-item label="附件:" style='align-items:flex-start;'>
                  <MOSTY.Upload v-model="fromObj.files" :widthNumber="726" :nopicer="true" :showinput="true" :limit="5"
                    :delrow="delrow" :showbut="true" :isEdit="fileEdit" @filehandleChange="changeFile"
                    :ShowfileList="true" :isImg="false" :placeholder="'请上传pdf,ofd, doc, docx,wps'"
                    :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'wps']" />
                </el-form-item>
              </el-form>
            </div>
          </div>
        </div>
      </template>
      <template #table>
        <!-- 监督活动列表 -->
        <div class="zl">
          <div class="headBox">
            <div class="title">监督活动列表</div>
            <div class="btns" style="display: flex;">
              <el-input placeholder="请输入活动名称或活动地点查询" v-model="listQuery.activityname" clearable></el-input>

              <el-button type="primary" @click="Searchname">
                <el-icon>
                  <Search />
                </el-icon>
                <span>查询</span>
              </el-button>
              <el-button type="primary" @click="addUserHander">
                <!-- v-if="addshow" -->
                <el-icon>
                  <CirclePlus />
                </el-icon>
                <span>新增</span>
              </el-button>


            </div>
          </div>
          <section :style="{ 'height': totalHeight }">
            <MOSTY.Table :table-columns="tableColumn" :tableData="tableData" :tableloading="tableloading"
              :isSelect="false" :isSort="true" @SortChange="SortChange" style="width: 100%;">
              <template #actions="{ row }">
                <!--  v-if="addshow" -->
                <span class="operedit" @click="editUserHander(row)"><el-icon>
                    <EditPen />
                  </el-icon>修改</span>
                <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
                  @confirm="handledelete(row)">
                  <!--  v-if="addshow" -->
                  <template #reference>
                    <span class="operdel" size="small"><el-icon>
                        <Delete />
                      </el-icon>删除</span>
                  </template>
                </el-popconfirm>
                <span class="operesee" @click="seeUserHander(row)"><el-icon>
                    <View />
                  </el-icon>查看</span>
              </template>
            </MOSTY.Table>
          </section>
          <div class="fenye">
            <MOSTY.Pages :pageConfiger="pageConfiger" @changeSize="handleSizeChange" @changeNo="handleCurrentChange">
            </MOSTY.Pages>
          </div>
        </div>
      </template>
    </MOSTY.PageTree>

    <!-- 修改 -->
    <div v-if="comprehensiveShow" class="dialog-box">
      <EditJdhd @close="close" :title="title" :rowId="rowId" :saveBtnShow="saveBtnShow" :orgcode="params.orgcode" />
    </div>
    <!-- 选择部门 -->
    <Choosebm :showDdld="showDept" :deptId='ssdept.ssdwid' @closezzjg="closezzjg" @listdata="getSonValue"
      :zzlx="zzlx" />
    <!-- 选择成员 -->
    <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :data="memberList" :leaderid="leaderid"
      :deptId="fromObj.deptid" @choosedUsers="getSonValue"></ChooseUser>
  </div>
</template>

<script setup>
import { getImgUrl } from "@/utils/tools.js"
import { onMounted, reactive, ref, nextTick } from "vue";
import EditJdhd from "./commponents/EditJdhd.vue";
import * as MOSTY from "@/components/MyComponents/index";
import { ElMessage } from "element-plus";
import Choosebm from "@/components/MyComponents/ChooseDept/index.vue";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import { getItem } from "@/utils/storage";
import { filterqx } from "@/utils/auth.js";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { getFileUrl } from "@/utils/getFile.js";
const params = reactive({ orgcode: "" });
const showBanner = ref(true)
const totalHeight = ref(null)
const getHeight = ref(null)
const imgList = ref([])
//规则校验
const rules = reactive({
  orgname: [{ required: true, message: "所属单位不能为空", trigger: "blur" }],
  deptname: [{ required: true, message: "所属部门不能为空", trigger: "blur" }],
  username: [{ required: true, message: "工会成员不能为空", trigger: "blur" }],
});
const keys = ref(1)
const ruleFormRef = ref()
const memberList = ref([]); //成员选择的id回显
const zzlx = ref(null);
const showDept = ref(false); //选择部门
const chooseUserVisible = ref(false);
const leaderid = ref("");
const singleShow = ref(true); //单选多选
const title = ref("监督活动新增");
const comprehensiveShow = ref(false);
const addshow = ref(false)
const ssdept = getItem("deptId");
const orgName = ref('')
const fromObj = ref({
  files: "",
  username: ""
});
const listQuery = reactive({
  pageCurrent: 1,
  pageSize: 10,
  activityname: ""
});
const rowId = ref(null);
const total = ref(0);
const tableColumn = ref([
  {
    title: "年度",
    prop: "activityname",
    sortable: true
  },
  {
    title: "活动地点",
    prop: "activitysite",
    sortable: true
  },
  {
    title: "开始时间",
    prop: "starttime",
    sortable: true
  },
  {
    title: "结束时间",
    prop: "endtime",
    sortable: true
  },
  {
    title: "添加人员",
    prop: "username",
    sortable: true
  },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
const pageConfiger = reactive({
  pageSize: 20,
  pageCurrent: 1,
  total: 0
})
//获取列表数据
const tableloading = ref(false);
// 初始化
onMounted(() => {
  nextTick(() => {
    totalHeight.value = `calc(100vh - ${230 + getHeight.value.offsetHeight}px)`
  })
});
//选择右侧部门
const getdeptId = (val) => {
  val.id = val.id.replace("XN", "")
  val.orgname = val.orgname.replace("(本级)", "")
  // 关闭上一次的表单校验
  fromObj.value.files = null;
  keys.value++
  ruleFormRef.value ? ruleFormRef.value.clearValidate() : '';
  listQuery.orgid = val.id;
  params.orgcode = val.id;
  orgName.value = val.orgname;
  listQuery.pageCurrent = 1;
  if (ssdept.orgLevel == '21' || ssdept.orgLevel == '11') {
    if (ssdept.ssdwid == val.id) {
      addshow.value = true
    } else {
      addshow.value = false
    }
  } else {
    if (ssdept.ssdwid == val.id) {
      addshow.value = true
    } else {
      addshow.value = false
    }
  }
  getListData();
  getghcy()
};
const close = () => {
  comprehensiveShow.value = false;
  rowId.value = null;
  getListData();
};
//搜索
const Searchname = () => {
  getListData();
};
// 切换工会成员数据和banner数据
function showGhcy() {
  showBanner.value = !showBanner.value
}
// 获取工会成员内容
function getghcy() {
  getApi(params, `/mosty-jcgl/Union/getUnion`).then((res) => {
    if (res) {
      fromObj.value = res;
    } else {
      fromObj.value = {}
      fromObj.value.orgid = listQuery.orgid
      fromObj.value.orgname = orgName.value
    }
  });
}
function getListData() {
  tableloading.value = true;
  imgList.value = []
  postApi(listQuery, "/mosty-jcgl/supervisionactivity/getPageList").then(async (res) => {
    if (res.records) {
      tableloading.value = false;
      tableData.value = res.records;
      pageConfiger.total = res.total;
      for (let j = 0; j < res.records.length; j++) {
        let arr = res.records[j].pics ? res.records[j].pics.split(",") : []
        let firstImg = arr[0];
        imgList.value.push({
          img: firstImg ? await getFileUrl(firstImg) : getImgUrl('img/emptyImg.jpg'),// 只放该行第一张图片
          id: res.records[j].id,
          activityname: res.records[j].activityname
        })
      }
      if (!imgList.value || imgList.value.length == 0) {
        imgList.value.push({
          img: getImgUrl('img/emptyImg.jpg')
        })
      }
    } else {
      tableData.value = [];
      tableloading.value = false;
      imgList.value.push({
        img: getImgUrl('img/emptyImg.jpg')
      })
    }
  }).finally(() => {
    tableloading.value = false;
  });
}
function ChooesDdld(val) {
  zzlx.value = val;
  if (val == '01') {
    showDept.value = true;
  } else {
    memberList.value = fromObj.value.userid ? fromObj.value.userid.split(',') : []
    chooseUserVisible.value = true;
    singleShow.value = false;
  }
}
const getSonValue = (value) => {
  if (zzlx.value == "01") {
    fromObj.value.deptname = value.orgName;
    fromObj.value.deptid = value.id;
  }
  if (zzlx.value == "02") {
    let arr = [];
    let arrid = [];
    for (let i = 0; i < value.length; i++) {
      const element = value[i];
      element.zzlx = zzlx.value;
      arr.push(element.userName);
      arrid.push(element.id);
    }
    memberList.value = value.map((item) => {
      return item.id;
    });
    fromObj.value.username = arr.toString(",");
    fromObj.value.userid = arrid.toString(",");
  }
};
const closezzjg = (val) => {
  showDept.value = val;
};
//分页
const handleSizeChange = (currentSize) => {
  listQuery.pageSize = currentSize;
  pageConfiger.pageSize = currentSize;
  getListData();
};
const handleCurrentChange = (currentPage) => {
  listQuery.pageCurrent = currentPage;
  pageConfiger.pageCurrent = currentPage;
  getListData();
};
const tableData = ref([
]);


// 方法
// 新增
const addUserHander = () => {
  title.value = "监督活动新增";
  rowId.value = null;
  comprehensiveShow.value = true;
  saveBtnShow.value = true;
};
//修改
const saveBtnShow = ref("");
const editUserHander = (row) => {
  saveBtnShow.value = true;
  title.value = "监督活动修改";
  rowId.value = row.id;
  comprehensiveShow.value = true;

};
//查询
const seeUserHander = (row) => {
  if(!row.id) return;
  saveBtnShow.value = false;
  title.value = "监督活动详情";
  rowId.value = row.id;
  comprehensiveShow.value = true;
};
const submit = async (formEl) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      fromObj.value.files = fromObj.value.files ? fromObj.value.files.toString() : null;
      if (fromObj.value.id) {
        postApi(fromObj.value, "/mosty-jcgl/Union/edit").then(() => {
          ElMessage.success("修改成功");
          getghcy();
        })
      } else {
        postApi(fromObj.value, "/mosty-jcgl/Union/add").then(() => {
          ElMessage.success("新增成功");
          getghcy();
        })
      }
    }
  })
}
//删除
const handledelete = (row) => {
  postApi({}, "/mosty-jcgl/supervisionactivity/del/" + row.id).then(() => {
    ElMessage.success("删除成功");
    getListData();
  });
};


</script>

<style lang="scss" scoped>
.bigBox {
  display: flex;

  .title {
    height: 35px;
    line-height: 35px;
    font-size: 18px;
    color: #0f3916;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .el-icon {
      cursor: pointer;
    }
  }


}


.wyh {
  border: 1px solid var(--el-color-primary);
  width: 100%;
  height: 30vh;


  .headBox {
    width: 100%;
    display: flex;
    justify-content: space-between;
    padding: 10px;
  }

  .imgbox {
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .form {
    overflow: auto;
    height: calc(30vh - 67px);
  }

  .head {
    display: flex;
    width: 100%;
    justify-content: space-between;
    align-items: center;
    border-bottom: 1px solid var(--el-color-primary);
    padding: 10px;
    box-sizing: border-box;
  }

  .el-form {
    width: 900px;
    padding: 10px;
    display: flex;
    justify-content: space-between;
    flex-wrap: wrap;
    box-sizing: border-box;

    .el-form-item {
      display: flex;
      align-items: center;
    }
  }
}

img {
  width: 100%;
  height: 30vh;
  object-fit: scale-down;
  background: #e0e0e0;
}

::v-deep .el-carousel__container {
  height: 30vh;
  padding: 0;
}
</style>
