<template>
  <el-dialog :title="props.title" width="1200px" v-model="dialogVisible" @close="dialogVisible = false">
    <el-form ref="ruleRef" label-width="130px" :model="ruleForm" label-suffix=":" :rules="rules"
      style="flex-wrap: wrap;width: 100% !important;" v-if="props.type == '01'">
      <el-row>
        <el-col :span="6">
          <el-form-item label="会议年度" prop="reportingYear">
            <el-select v-model="ruleForm.reportingYear" clearable>
              <el-option v-for="item in filterYear(5)" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="上/下半年" prop="jd">
            <el-select v-model="ruleForm.jd" clearable placeholder="请选择上/下半年" style="width: 400px"
              @change="retrievalTimes">
              <el-option label="上半年" value='1' />
              <el-option label="下半年" value='2' />
            </el-select>
            <!-- <MOSTY.DictRidioAndSelect :dictData="D_BZ_QUARTER" v-model="ruleForm.jd" selectType="select"
              style="width: 100%" /> -->
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="会议时间" prop="meetingDate">
            <el-date-picker v-model="ruleForm.meetingDate" type="daterange" range-separator="至" start-placeholder="开始日期"
              end-placeholder="结束日期" value-format="YYYY-MM-DD" style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="会议名称" prop="meetingName">
            <el-input v-model="ruleForm.meetingName" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="18">
          <span class="fr">
            <el-button @click="onRest">重置</el-button>
            <el-button type="primary" @click="pageData"> 查询 </el-button>
            <el-button type="primary" @click="onAdd"> 新增 </el-button>
          </span>
        </el-col>
      </el-row>
    </el-form>
    <el-table :data="tableData" style="width: 100%; margin-bottom: 10px" v-loading="tableLoading"
      :header-cell-style="{ background: '#F6F6F6' }" height="50vh">
      <el-table-column type="index" label="序号" width="55" fixed />
      <el-table-column prop="meetingName" label="会议名称" width="200" fixed />
      <el-table-column prop="reportingYear" label="年度" />
      <el-table-column label="上/下半年">
        <template #default="scope">
          {{jdArr.find((item) => item.value == scope.row.jd)?.label}}
        </template>
      </el-table-column>
      <el-table-column prop="meetingConveneDate" label="会议时间" />
      <el-table-column label="操作" width="140" fixed="right">
        <template #default="{ row }">
          <el-link type="primary" @click="onDetail(row)">详情</el-link>
          <el-link type="primary" @click="onEdit(row)">编辑</el-link>
          <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
            @confirm="onDelete(row)">
            <template #reference>
              <el-link type="danger">删除</el-link>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="flex just-center" v-if="props.type == '01'">
      <el-pagination class="pagination" @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="ruleForm.pageCurrent" :page-sizes="[2, 5, 10, 20]" :page-size="ruleForm.pageSize"
        layout="total, prev, pager, next, sizes, jumper" :total="total"></el-pagination>
    </div>
  </el-dialog>


  <el-dialog :title="dType + props.title" width="700px" v-model="detailVisible" :before-close="onClose">
    <el-form ref="ruleFormRef" label-width="130px" :model="detailForm" label-suffix=":" :rules="rules"
      style="flex-wrap: wrap" :disabled="dType.includes('查看') ? true : false">
      <el-row>
        <el-col :span="12">
          <el-form-item label="会议年度" prop="reportingYear">
            <el-select v-model="detailForm.reportingYear" clearable disabled readonly>
              <el-option v-for="item in filterYear(5)" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="上/下半年" prop="jd">
            <el-select v-model="detailForm.jd" clearable placeholder="请选择上/下半年" style="width: 400px">
              <el-option label="上半年" value='1' />
              <el-option label="下半年" value='2' />
            </el-select>
            <!-- <MOSTY.DictRidioAndSelect :dictData="D_BZ_QUARTER" v-model="detailForm.jd" selectType="select"
              style="width: 100%" /> -->
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="会议时间" prop="meetingConveneDate">
            <el-date-picker v-model="detailForm.meetingConveneDate" type="date" value-format="YYYY-MM-DD"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="会议名称" prop="meetingName">
            <el-input v-model="detailForm.meetingName" clearable />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="24">
          <el-form-item label="会议人员" prop="username" style="display: flex;">
            <el-input type="textarea" v-model="detailForm.username" autosize style="margin-right:5px;width: 81%;" />
            <el-button type="primary" @click="ChooesDdld('01')">选择</el-button>
          </el-form-item>
        </el-col> -->
        <el-col :span="24">
          <el-form-item label="签到表附件">
            <MOSTY.Upload :widthNumber="530" :limit="20" :nopicer="true" :isImg="false" :ShowfileList="true"
              v-model="detailForm.signin" :showinput="true"></MOSTY.Upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="会议纪要附件">
            <MOSTY.Upload :widthNumber="530" :limit="20" :nopicer="true" :isImg="false" :ShowfileList="true"
              v-model="detailForm.files" :showinput="true"></MOSTY.Upload>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="会议图片附件">
            <!-- <MOSTY.Upload :width="917" :limit="3" :nopicer="false" :isImg="true" :ShowfileList="false"
              v-model="detailForm.pics" :nameshow="true" :gsgfList="['jpg', 'png']" :disabled="!props.saveBtnShow"> -->
            <MOSTY.Upload :widthNumber="530" :limit="3" :nopicer="false" :isImg="true" :ShowfileList="true"
              v-model="detailForm.pics" :showinput="true"></MOSTY.Upload>
          </el-form-item>
        </el-col>
        <!-- <el-col :span="24">
          <el-form-item label="备注" prop="bz">
            <el-input type="textarea" v-model="detailForm.bz" clearable />
          </el-form-item>
        </el-col> -->
      </el-row>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="saveForm" v-if="!dType.includes('查看')" style="margin-right: 10px">保存</el-button>
        <el-button @click="onClose">取消</el-button>
      </span>
    </template>



    <!-- 选择带队领导 -->
    <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :data="memberList" :leaderid="leaderid"
      :deptId="orgcodes" @choosedUsers="getSonValue"></ChooseUser>
  </el-dialog>


  <el-dialog :title="props.title" width="700px" v-model="detailVisible2">
    <el-form ref="ruleFormRefs" label-width="130px" :model="detailForm2" label-suffix=":" style="flex-wrap: wrap"
      disabled>
      <el-row>
        <el-col :span="12">
          <el-form-item label="会议年度" prop="reportingYear">
            <el-select v-model="detailForm2.reportingYear" clearable>
              <el-option v-for="item in filterYear(5)" :key="item.value" :label="item.label"
                :value="item.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="会议季度" prop="jd">
            <MOSTY.DictRidioAndSelect :dictData="D_BZ_QUARTER" v-model="detailForm2.jd" selectType="select"
              style="width: 100%" />

          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="会议时间" prop="meetingConveneDate">
            <el-date-picker v-model="detailForm2.meetingConveneDate" type="date" value-format="YYYY-MM-DD"
              style="width: 100%" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="会议名称" prop="meetingName">
            <el-input v-model="detailForm2.meetingName" clearable />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="会议附件">
            <MOSTY.Upload :widthNumber="530" :nopicer="true" :isImg="false" :ShowfileList="true"
              v-model="detailForm2.attachments" :showinput="true"></MOSTY.Upload>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

  </el-dialog>

</template>

<script setup>
import { onMounted, ref, reactive, getCurrentInstance, watch } from "vue";
import * as MOSTY from "@/components/MyComponents/index";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { filterYear } from "@/utils/auth.js";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import { ElMessage } from "element-plus";
const props = defineProps({ title: String, rowItem: Object, queryItem: Object, type: String });
const dialogVisible = ref(false);
const { proxy } = getCurrentInstance()
const { D_BZ_QUARTER } =
  proxy.$dict("D_BZ_QUARTER")
const ruleFormRef = ref();
const leaderid = ref(null);
const chooseUserVisible = ref(false);
const singleShow = ref(true); //单选多选
const dType = ref("")
const orgcodes = ref('')
const ruleForm = ref({
  reportingYear: "",
  jd: "",
  meetingDate: [],
  meetingName: "",
  pageCurrent: 1,
  pageSize: 10
});
const jdArr = [
  {
    label: "上半年",
    value: "1"
  },
  {
    label: "下半年",
    value: "2"
  },
  // {
  //   label: "第三季度",
  //   value: "3"
  // },
  // {
  //   label: "第四季度",
  //   value: "4"
  // }
];
const rules = reactive({
  reportingYear: [{ required: true, message: "会议年度不能为空", trigger: "blur" }],
  jd: [{ required: true, message: "会议上/下半年不能为空", trigger: "blur" }],
  meetingConveneDate: [{ required: true, message: "会议时间不能为空", trigger: "blur" }],
  meetingName: [{ required: true, message: "会议名称不能为空", trigger: "blur" }]
});
const emit = defineEmits(["close"]);
const tableLoading = ref(false);
const total = ref(0);
const tableData = ref([]);
const memberList = ref([]); //成员选择的id回显
const zzlx = ref(null);
const detailVisible = ref(false);
const detailVisible2 = ref(false);
const detailForm = ref({
  year: "",
  jd: "",
  meetingDate: "",
  meetingName: "",
  meetingPeople: "1,2,3",
  attachments: null,
  remark: ""
});
const detailForm2 = ref({})
// const emit = defineEmits(["onSave"]);
defineExpose({ dialogVisible });

const onRest = () => {
  ruleForm.value = {
    reportingYear: props.queryItem.year,
    jd: "",
    meetingDate: [],
    meetingName: "",
    pageCurrent: 1,
    pageSize: 10
  };
  pageData();
};
onMounted(() => {


  // getStandardScore();
});
watch(
  () => dialogVisible.value,
  (n, o) => {
    if (n) {
      orgcodes.value = props.rowItem.orgCode && props.rowItem.orgCode.replace('XN', '')
      ruleForm.value.reportingYear = props.queryItem.year;
      pageData();
    }
  },
  { deep: true }
  // { immediate: true, deep: true }
);
function closed() {
  emit("close", true);
}
const onDetail = (row) => {
  dType.value = "查看"
  if (props.type == '01') {
    detailVisible.value = true;
    detailForm.value = JSON.parse(JSON.stringify(row))
    // getApi({ id: row.lyid }, "/mosty-jcgl/data/meetingInfo/getDetailById").then((res) => {
    //   if (res) {
    //     detailForm.value = res;
    //   }
    // });
  } else {
    detailVisible2.value = true
    getApi({ id: row.sourceId }, "/mosty-jcgl/data/meetingInfo/getLsjlDetail").then((res) => {
      if (res) {
        detailForm2.value = res;

      }
    });
  }

};
function ChooesDdld(val) {
  zzlx.value = val;
  if (val == "01" && detailForm.value.userid) {
    memberList.value = detailForm.value.userid.split(',')
  }
  chooseUserVisible.value = true;
  singleShow.value = false;
}
const getSonValue = (value) => {
  if (zzlx.value == "01") {
    let arr = [];
    let arrid = [];
    for (let i = 0; i < value.length; i++) {
      const element = value[i];
      element.zzlx = zzlx.value;
      arr.push(element.userName + "(" + element.deptName + ")");
      arrid.push(element.id);
    }
    memberList.value = value.map((item) => {
      return item.id;
    });
    detailForm.value.username = arr.join(",");
    detailForm.value.userid = arrid.join(",");
  }
};
const handleSizeChange = (val) => {
  ruleForm.value.pageSize = val;
  pageData();
};
const handleCurrentChange = (val) => {
  ruleForm.value.pageCurrent = val;
  pageData();
};
const onAdd = () => {
  detailVisible.value = true
  dType.value = "新增"
  detailForm.value = {
    reportingYear: new Date().getFullYear(),
  }
}
const onEdit = row => {
  detailForm.value = JSON.parse(JSON.stringify(row))
  detailVisible.value = true
  dType.value = "编辑"
}
const onDelete = row => {
  postApi([row.sourceId], "/mosty-jcgl/data/meetingInfo/delDataMeetingInfo").then(res => {
    if (res) {
      ElMessage({
        message: "删除成功",
        type: "success"
      })
      pageData()
    }
  })
}
const pageData = () => {
  tableLoading.value = true;
  tableData.value = [];
  if (props.type == '01') {
    ruleForm.value.orgcode = props.rowItem.orgCode;
    if (ruleForm.value.meetingDate.length > 0) {
      ruleForm.value.start = ruleForm.value.meetingDate[0];
      ruleForm.value.end = ruleForm.value.meetingDate[0];
    }
    postApi(ruleForm.value, "/mosty-jcgl/data/meetingInfo/getListDetail").then((res) => {
      if (res) {
        tableData.value = res.records;
        tableLoading.value = false;
        total.value = res.total || 0
      }
    });
  } else {
    let obj = {}
    obj.cs = props.rowItem.sbcs
    obj.orgcode = props.rowItem.orgCode
    obj.year = props.queryItem.year

    postApi(obj, "/mosty-jcgl/data/meetingInfo/getLsjlList").then((res) => {
      if (res) {
        tableData.value = res;
        tableLoading.value = false;
      }
    });
  }

};
const saveForm = async () => {
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      detailVisible.value = true
      detailForm.value.files = detailForm.value.files ? detailForm.value.files.toString() : ''
      detailForm.value.signin = detailForm.value.signin ? detailForm.value.signin.toString() : ''
      detailForm.value.pics = detailForm.value.pics ? detailForm.value.pics.toString() : ''
      if (detailForm.value.attachments) detailForm.value.attachments = detailForm.value.attachments.toString()
      if (dType.value.includes("新增")) {
        detailForm.value.orgCode = props.rowItem.orgCode
        detailForm.value.orgName = props.rowItem.orgName
        const params = {
          ...detailForm.value,
          // operationType: 1
          status: 0,
          // lyid: props.rowItem.id,
          updateFlag: 1 // 状态 1.新增 2.修改 3.删除
        }
        postApi(params, "/mosty-jcgl/data/meetingInfo/saveDataMeetingInfo").then(res => {
          if (res) {
            detailVisible.value = false
            ElMessage({
              message: "新增成功",
              type: "success"
            })
            pageData()
          }
        })
      }
      if (dType.value.includes("编辑")) {
        postApi(detailForm.value, "/mosty-jcgl/data/meetingInfo/editDataMeetingInfo").then(res => {
          if (res) {
            detailVisible.value = false
            ElMessage({
              message: "保存成功",
              type: "success"
            })
            pageData()
          }
        })
      }
    } else {
      ElMessage.warning('请输入必填项！！！')
    }
  })

}

const onClose = () => {
  if (!dType.value.includes('查看')) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        detailVisible.value = false
      })
      .catch(() => {
        // catch error
      })
  } else {
    detailVisible.value = false
  }

};
</script>

<style lang="scss" scoped>
::v-deep .el-dialog__body {
  height: 72vh !important;
}

.content {
  .topper {
    display: flex;

    .sub-le {
      flex: 1;
      padding: 15px 15px 5px 15px;
      border-right: 1px solid #ebeef5;
    }
  }

  .bottom {
    padding: 0 15px 10px 15px;
  }
}
</style>
