<template>
  <div class="bigBoxs">
    <MOSTY.FromPage :title="props.title" @closeDialog="CloseEvent">
      <template #content>
        <MOSTY.Assort :title="'基础信息'" />
        <el-form class="mosty-from-wrap" ref="ruleFormRef" label-width="130px" :model="data.fromObj" :inline="true"
          :rules="rules" :disabled="!props.saveBtnShow">
          <el-form-item label="消防队名称:" prop="firebrigadename">
            <el-input v-model="data.fromObj.firebrigadename" clearable style="width: 337px" />
          </el-form-item>
          <el-form-item label="消防队类型:" prop="firebrigadetype">
            <el-select v-model="data.fromObj.firebrigadetype" style="width: 337px" clearable placeholder="请选择消防队类型：">
              <el-option v-for="item in D_BZ_XFDLX" :key="item" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="消防队单位:" prop="orgname">
            <el-input v-model="data.fromObj.orgname" style="width: 337px" readonly disabled="true">
              <!-- <template #append>
                <el-button type="primary" @click="ChooesDdld('02')" disabled="true">选择</el-button>
              </template> -->
            </el-input>
          </el-form-item>
          <el-form-item label="成立时间:" prop="establishtime">
            <el-date-picker v-model="data.fromObj.establishtime" style="width: 337px" type="date"
              :disabled-date="disablednowDate1" value-format="YYYY-MM-DD" />
          </el-form-item>
          <el-form-item label="最近调整时间:" prop="adjusttime">
            <el-date-picker v-model="data.fromObj.adjusttime" style="width: 337px" type="date"
              :disabled-date="disablednowDate1" value-format="YYYY-MM-DD" />
          </el-form-item>

          <el-form-item label="备注:">
            <el-input v-model="data.fromObj.bz" clearable style="width: 337px" />
          </el-form-item>
        </el-form>
        <MOSTY.Assort v-if="props.rowId" :title="'消防队成员信息'" />
        <div v-if="props.rowId && props.saveBtnShow">
          <el-button class="addbtn" type="primary" @click="addInfo('add', null)">
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>新增</span>
          </el-button>
        </div>
        <section v-if="props.rowId" style="height: 40vh;">
          <MOSTY.Table :table-columns="tableColumn" :tableData="tbFireMembersList" :tableloading="tableloading"
            :isSelect="false" :isSort="false" @SortChange="SortChange" style="width: 100%;">
            <template #membersex="{ row }">
              <dict-tag v-if="row.membersex" :options="D_BZ_XB" :value="row.membersex" :tag="false" />
              <span v-else>无</span>
            </template>
            <template #fireposition="{ row }">
              <dict-tag v-if="row.fireposition" :options="D_BZ_XFZW" :value="row.fireposition" :tag="false" />
              <span v-else>无</span>
            </template>
            <template #politiclandscape="{ row }">
              <dict-tag v-if="row.politiclandscape" :options="D_BZ_AQRYZZMM" :value="row.politiclandscape"
                :tag="false" />
              <span v-else>无</span>
            </template>
            <template #actions="{ row }">
              <span class="operedit" v-if='props.saveBtnShow' @click="addInfo('exit', row.id)"><el-icon>
                  <EditPen />
                </el-icon>编辑</span>
              <span class="operesee" v-if='!props.saveBtnShow' @click="addInfo('see', row.id)"><el-icon>
                  <Compass />
                </el-icon>查看</span>
              <el-popconfirm confirm-button-text="是" cancel-button-text="否" icon-color="red" title="确定要删除?"
                v-if='props.saveBtnShow' @confirm="delInfo(row.id)">
                <template #reference>
                  <span class="operdel" size="small"><el-icon>
                      <Delete />
                    </el-icon>删除</span>
                </template>
              </el-popconfirm>
            </template>
          </MOSTY.Table>
        </section>
        <div v-if="props.rowId" class="fenye">
          <MOSTY.Pages :pageConfiger="pageConfiger" @changeSize="handleSizeChange" @changeNo="handleCurrentChange">
          </MOSTY.Pages>
        </div>

      </template>
      <template #footer>

        <el-button type="primary" :loading="loading" @click="handleSave(ruleFormRef)" v-if="props.saveBtnShow">
          <span><el-icon>
              <DocumentChecked />
            </el-icon>
            保存</span>
        </el-button>
        <el-button @click="CloseEvent" type="primary">
          <span><el-icon>
              <DocumentDelete />
            </el-icon>关闭</span>
        </el-button>
      </template>
      <template #dwbox>
        <el-dialog v-model="dialogVisible" :title="data.title" :close-on-click-modal="false" width="850px"
          :before-close="handleClose">
          <el-form class="mosty-from-wrap" ref="elform" label-width="130px" :model="fromObj" :inline="true"
            :rules="rules2" :disabled="!props.saveBtnShow">
            <el-form-item label="姓名:" prop="membername">
              <el-input v-model="fromObj.membername" style="width: 250px" readonly>
                <template #append>
                  <el-button @click="ChooesDdld('01')" style="color:var(--el-color-primary)">选择</el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="所属部门/相关方:">
              <el-input v-model="fromObj.memberorgname" disabled clearable style="width: 250px" />
            </el-form-item>
            <el-form-item label="性别:" prop="membersex">
              <el-select v-model="fromObj.membersex" style="width: 250px" clearable placeholder="请选择性别：">
                <el-option v-for="item in D_BZ_XB" :key="item" :label="item.label" :value="item.value" readonly />
              </el-select>
            </el-form-item>
            <!-- <el-form-item label="政治面貌:" prop="politiclandscape">
              <el-select v-model="fromObj.politiclandscape" style="width: 250px" clearable placeholder="请选择政治面貌：">
                <el-option v-for="item in D_BZ_AQRYZZMM" :key="item" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="行政职务:" prop="administrativeposition">
              <el-input v-model="fromObj.administrativeposition" clearable style="width: 250px" />
            </el-form-item> -->
            <el-form-item label="消防职务:" prop="fireposition">
              <el-select v-model="fromObj.fireposition" style="width: 250px" clearable placeholder="请选择消防职务：">
                <el-option v-for="item in D_BZ_XFZW" :key="item" :label="item.label" :value="item.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="入队时间:" prop="enqueuetime">
              <el-date-picker v-model="fromObj.enqueuetime" style="width: 250px" type="date"
                :disabled-date="disablednowDate1" value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="备注:">
              <el-input v-model="fromObj.bz" clearable style="width: 650px" />
            </el-form-item>
          </el-form>
          <template #footer>
            <span class="dialog-footer">

              <el-button type="primary" @click="submitry(elform)" v-if="props.saveBtnShow" :loading="loadingzb">
                <el-icon>
                  <DocumentChecked />
                </el-icon>
                保存
              </el-button>
              <el-button @click="handleClose"><el-icon>
                  <DocumentDelete />
                </el-icon>关闭</el-button>
            </span>
          </template>
        </el-dialog>
        <!-- 选择带队领导 -->
        <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :data="memberList" :deptId="data.fromObj.orgid"
          :leaderid="leaderid" @choosedUsers="getSonValue" :isNewChooseDept="true"></ChooseUser>
        <Choosebm :formInfo="data.fromObj" :showDdld="showDept" @closezzjg="closeJhss" @listdata="getSonValue"
          :Isstrictly="true" :zzlx="zzlx" />
        <ChooseOrg :formInfo="data.fromObj" :showDdld="showOrg" @closezzjg="closeorg" @listdata="getSonValue"
          :zzlx="zzlx" />
      </template>
    </MOSTY.FromPage>
  </div>


</template>

<script setup>
import { ref, onMounted, defineProps, defineEmits, reactive, watchEffect, getCurrentInstance } from "vue";
import ChooseOrg from "@/components/MyComponents/ChooseOrg/index.vue";
import * as MOSTY from "@/components/MyComponents/index";
import Choosebm from "@/components/MyComponents/ChooseDept/index.vue";
import { ElMessage } from "element-plus";
import { disablednowDate1 } from '@/utils/tools.js'
import { postApi, getApi } from "@/api/tobAcco_api.js";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import { getItem } from "@/utils/storage";
const { proxy } = getCurrentInstance();
const { D_BZ_XFDLX, D_BZ_XFZW, D_BZ_XB, D_BZ_AQRYZZMM } = proxy.$dict(
  "D_BZ_XFDLX", "D_BZ_XFZW", "D_BZ_XB", "D_BZ_AQRYZZMM");
const rules = reactive({
  firebrigadename: [{ required: true, message: "消防队不能为空", trigger: "blur" }],
  firebrigadetype: [{ required: true, message: "请选择消防队类型", trigger: "blur" }],
  orgname: [{ required: true, message: "消防队单位不能为空", trigger: "blur" }],
  relatedName: [{ required: true, message: "消防队单位不能为空", trigger: "blur" }],
  establishtime: [{ required: true, message: "请选择成立时间", trigger: "blur" }],
  adjusttime: [{ required: true, message: "请选择最近调整时间", trigger: "blur" }]
});
const rules2 = reactive({
  membername: [{ required: true, message: "请选择成立姓名", trigger: "blur" }],
  membersex: [{ required: true, message: "请选择性别", trigger: "blur" }],
  politiclandscape: [{ required: true, message: "请选择政治面貌", trigger: "blur" }],
  administrativeposition: [{ required: true, message: "行政职务不能为空", trigger: "blur" }],
  fireposition: [{ required: true, message: "请选择消防职务", trigger: "blur" }],
  enqueuetime: [{ required: true, message: "请选择入队时间", trigger: "blur" }]
});
const props = defineProps({
  title: {
    type: String,
    default: ""
  },
  saveBtnShow: {
    type: Boolean,
    default: true
  },
  deptData: {
    type: Object,
    default: {}
  },
  rowId: {
    type: String,
    default: ""
  },
});
const showDept = ref(false);
const loading = ref(false);
const loadingzb = ref(false);
const tbFireMembersList = ref([])
const emits = defineEmits(["close"]);
const dialogVisible = ref(false);
const fromObj = ref({});
const chooseUserVisible = ref(false); //选择领导弹窗
const singleShow = ref(true); //单选多选
const memberList = ref([]); //成员选择的id回显
const leaderid = ref("");
const zzlx = ref(null);
const isRelatedStatus = ref(false)
const pageConfiger = reactive({
  pageSize: 10,
  pageCurrent: 1,
  total: 0
})
const tableColumn = ref([
  {
    title: "姓名",
    prop: "membername",
  },
  {
    title: "性别",
    prop: "membersex",
    slot: true
  },
  {
    title: "消防职务",
    prop: "fireposition",
    slot: true
  },
  // {
  //   title: "政治面貌",
  //   prop: "politiclandscape",
  //   slot: true
  // },
  // {
  //   title: "行政职务",
  //   prop: "administrativeposition",
  // },
  {
    title: "入队时间",
    prop: "enqueuetime"
  },
  {
    title: "所属部门/相关方",
    prop: "memberorgname"
  },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])

onMounted(() => {
  if (props.rowId) {
    getmain(props.rowId)
  } else {
    data.fromObj = {}
  }
  if (Object.keys(props.deptData).length) {
    data.fromObj.orgid = props.deptData.orgid
    data.fromObj.orgname = props.deptData.orgname
  }
});
//详情
const getmain = (id) => {
  if (id) {
    getApi(
      {},
      "/mosty-jcgl/fireInformation/getTbFireInformationById/" + id
    ).then((res) => {
      if (res) {
        data.fromObj = res;
        if (data.fromObj.file) {
          if (data.fromObj.file.index0f("[") != -1) {
            data.fromObj.file = JSON.parse(data.fromObj.file);
          } else {
            data.fromObj.file = data.fromObj.file.split(",");
          }
        }
        getxfdcylist()
      }
    });

  }
};
//查看消防队成员
function getxfdcylist() {
  //消防队成员
  getApi({ id: data.fromObj.id, pageCurrent: pageConfiger.pageCurrent, pageSize: pageConfiger.pageSize },
    "/mosty-jcgl/fireMembers/queryFireMembersById").then(
      (res) => {
        if (res) {
          tbFireMembersList.value = res.records;
          pageConfiger.total = res.total
        }
      }
    );
}
const CloseEvent = () => {
  if (props.saveBtnShow) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        // 关闭上一次的表单校验
        ruleFormRef.value.clearValidate();
        emits("close");
      })
      .catch(() => {
        // catch error
      })
  } else {
    // 关闭上一次的表单校验
    ruleFormRef.value.clearValidate();
    emits("close");
  }

};
function handleClose(params) {
  if (props.saveBtnShow) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        dialogVisible.value = false
      })
      .catch(() => {
        // catch error
      })
  } else {
    dialogVisible.value = false
  }
}

const data = reactive({
  fromObj: {}
});
const showOrg = ref(false)
//点击带队领导选择按钮
function ChooesDdld(val) {
  zzlx.value = val;
  leaderid.value = "";
  if (val == "01") {
    leaderid.value = fromObj.value.memberid;
    singleShow.value = true;
    chooseUserVisible.value = true;
  }
  if (val == "02") {
    showDept.value = true;
  }
  if (val == "03") {
    showOrg.value = true
  }
}
const getSonValue = (value) => {
  console.log(value)
  if (zzlx.value == "01") {
    // 1 部门成员 2相关方
    if (value.memberType === 2) {
      fromObj.value.membername = value[0].userName;
      fromObj.value.memberid = value[0].id;
      fromObj.value.membersex = value[0].sex;
      fromObj.value.memberorgcode = value[0].deptId;
      fromObj.value.memberorgname = value[0].deptName;
    } else {
      fromObj.value.membername = value[0].userName;
      fromObj.value.memberid = value[0].id;
      fromObj.value.membersex = value[0].sex;
      fromObj.value.politiclandscape = value[0].politic;
      fromObj.value.memberorgcode = value[0].deptId;
      fromObj.value.memberorgname = value[0].deptName;
    }
  } else if (zzlx.value == "02") {
    data.fromObj.orgname = value.orgName;
    data.fromObj.orgid = value.id;
  } else if (zzlx.value == "03") {
    data.fromObj.orgname = value.orgName
    data.fromObj.orgid = value.id
  }
};
const closeJhss = (val) => {
  showDept.value = val;
};
const closeorg = (val) => {
  showOrg.value = val;
};

//新增
function addInfo(type, id) {
  if (type == 'add') {
    fromObj.value = {};
    fromObj.value.informationid = data.fromObj.id
    data.title = "消防队成员新增";
  } else if (type == 'exit') {
    data.title = "消防队成员修改";
    getxfryxq(id)
  } else {
    data.title = "消防队成员查看";
    getxfryxq(id)
  }

  dialogVisible.value = true;

}
function getxfryxq(id) {
  getApi({}, `/mosty-jcgl/fireMembers/getFireMembersById/${id}`).then(res => {
    fromObj.value = res
  })
}
//删除
function delInfo(id) {
  postApi({}, `/mosty-jcgl/fireMembers/del/${id}`).then(res => {
    ElMessage.success("删除成功");
    getxfdcylist();
  })

}
const elform = ref();
//新增修改完毕
const submitry = async (elform) => {
  console.log(fromObj.value)
  if (!elform) return;
  await elform.validate((valid) => {
    if (valid) {
      loadingzb.value = true
      if (fromObj.value.id) {
        postApi(fromObj.value, '/mosty-jcgl/fireMembers/edit').then(res => {
          ElMessage.success("修改成功");
        }).finally(() => {
          dialogVisible.value = false;
          loadingzb.value = false
          getxfdcylist()
        })

      } else {
        postApi(fromObj.value, '/mosty-jcgl/fireMembers/add').then(res => {
          ElMessage.success("新增成功");
        }).finally(() => {
          dialogVisible.value = false;
          loadingzb.value = false
          getxfdcylist()
        })
      }

    } else {
      ElMessage.error("请输入必填项!”");
    }
  });
};
const ruleFormRef = ref();
// 保存
const handleSave = async (ruleFormRef) => {
  if (!ruleFormRef) return;
  await ruleFormRef.validate((valid) => {
    if (valid) {
      loading.value = true
      if (data.fromObj) {
        if (data.fromObj.id) {
          postApi(
            data.fromObj,
            "/mosty-jcgl/fireInformation/updateFireInformationOne"
          )
            .then((res) => {
              ElMessage.success("修改成功");
              emits("close");
            }).finally(() => {
              loading.value = false
            })

        } else {
          postApi(
            data.fromObj,
            "/mosty-jcgl/fireInformation/addFireInformationOne"
          )
            .then((res) => {
              ElMessage.success("新增成功");
              emits("close");
            }).finally(() => {
              loading.value = false
            })
        }
      }
    } else {
      ElMessage.error("请输入必填项!");
    }
  });
};

const handleSizeChange = (currentSize) => {
  pageConfiger.pageSize = currentSize;
  getxfdcylist();
};
const handleCurrentChange = (currentPage) => {
  pageConfiger.pageCurrent = currentPage;
  getxfdcylist();
};
</script>

<style lang="scss" scoped>
.box_cont {
  height: calc(100vh - 10vh);
  overflow-y: scroll;
}

.searchBox {
  width: 1333px;
  margin: 20px auto;
}

.el-form {
  width: 100%;
  align-items: center;
  display: flex;
  justify-content: flex-start;
  flex-wrap: wrap;
  margin: 20px;
}

.el-form-item {
  display: flex;
  margin-right: 20px;
}

.addbtn {
  margin-bottom: 10px;
}

.bigBox {
  display: block !important;
  padding: 0 14px;
  box-sizing: border-box;
}

.tabbox {
  max-height: 300px;
  overflow-y: scroll;

  .input {
    width: 100%;
    height: 100%;
  }
}

::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;
  }
}

::v-deep .el-upload-list {
  width: 50%;
}
</style>