<template>
  <div class="bigBox">
    <MOSTY.FromPage :title="pageTitle" @closeDialog="black">
      <template #content>
        <MOSTY.Assort :title="'基本信息'" />
        <div class="fromBox">
          <el-form ref="ruleFormRef" :model="data.formData" :rules="rules" :disabled="!saveBtn" class="mosty-from-wrap"
            label-width="140px" :inline="true">
            <el-form-item label="单位名称:" prop="orgname">
              <el-input v-model="data.formData.orgname" readonly style="width: 337px"></el-input>
            </el-form-item>
            <el-form-item label="部门:" prop="deptname" style="display: flex;">
              <el-input v-model="data.formData.deptname" readonly clearable style="width: 337px">
                <template #append>
                  <el-button class='cursor' @click="ChooesDdld('01')">选择</el-button></template>
              </el-input>
            </el-form-item>
            <el-form-item label="发放日期:" prop="time">
              <el-date-picker v-model="data.formData.time" type="date" value-format="YYYY-MM-DD" style="width: 337px"
                placeholder="请选择发放日期" />
            </el-form-item>
            <el-form-item label="发放防护用品内容:" prop="content" style="width:100%;">
              <el-input v-model="data.formData.content" type="textarea" autosize style="width: 100%"></el-input>
            </el-form-item>
            <el-form-item label="附件:" style="width:100%;">
              <MOSTY.Upload :isAutoWidth="true" stringify :limit="5" :nopicer="true" :isImg="false" :ShowfileList="true"
                v-model="data.formData.file" :placeholder="'请上传pdf,ofd, doc, docx,wps或 图片'"
                :gsgfList="['pdf', 'ofd', 'doc', 'docx', 'png', 'jpg', 'jpeg', 'gif', 'bmp','wps']" :showinput="true"
                :delrow="delrow">
              </MOSTY.Upload>

            </el-form-item>
          </el-form>
          <div v-if="data.formData.id">
            <MOSTY.Assort :title="'防护用品清单'" />
            <div class=" mb10" v-if="saveBtn">
              <el-button class="mr10" type="primary" @click="addypqd('add')">
                <el-icon>
                  <CirclePlus />
                </el-icon>
                <span>新增</span>
              </el-button>
              <el-button class="mr10" type="primary" @click="downloadTemplate('08', '劳动防护用品清单-导入模板')">
                <el-icon>
                  <Download />
                </el-icon>
                <span>模板下载</span>
              </el-button>
              <el-button type="primary" @click="uploadFile">
                <el-icon>
                  <UploadFilled />
                </el-icon>
                <span>批量导入</span>
              </el-button>
              <!-- 文件上传小东西 -->
              <input type="file" style="display: none;" @change="changeFile" ref="fileBtn">
            </div>
            <section class="eltabs4">
              <MOSTY.Table :table-columns="tabColumns" :tableloading="tableloading" :tableData="tableData"
                :tableHeight="'100%'" :isSelect="false" style="width: 100%;" :isSort="true">
                <template #unit="{ row }">
                  <dict-tag v-if="row.unit" :options="D_BZ_WPDW" :value="row.unit" :tag="false" />
                  <span v-else>无</span>
                </template>
                <template #actions="{ row }">
                  <span class="operedit" v-if="saveBtn" @click="addypqd('exit', row.id)" size="small"><el-icon>
                      <EditPen />
                    </el-icon>修改</span>
                  <el-popconfirm v-if="saveBtn" confirm-button-text="是" cancel-button-text="否" icon-color="red"
                    title="确定要删除?" @confirm="delte(row)">
                    <template #reference>
                      <span class="operdel" style="color: yellowgreen" size="small">
                        <el-icon>
                          <Delete />
                        </el-icon>删除</span>
                    </template>
                  </el-popconfirm>
                  <span class="operesee" @click="addypqd('see', row.id)" size="small"><el-icon>
                      <View />
                    </el-icon>查看</span>
                </template>
              </MOSTY.Table>
              <div class="fenye">
                <MOSTY.Pages :pageConfiger="pageConfiger" @changeNo="changeNo" @changeSize="changeSize">
                </MOSTY.Pages>
              </div>
            </section>
          </div>
        </div>
      </template>
      <template #footer>

        <el-button v-if="saveBtn" type="primary" v-loading='loadingshow' @click="submit(ruleFormRef)">
          <el-icon>
            <DocumentChecked />
          </el-icon>保存
        </el-button>
        <el-button @click="black">
          <el-icon>
            <DocumentChecked />
          </el-icon>关闭</el-button>
      </template>
      <template #dwbox>
        <!-- 选择部门 -->
        <Choosebm v-if='showDept' :showDdld="showDept" @closezzjg="closezzjg" @listdata="getSonValue" :zzlx="zzlx"
          :searchType="'01'" :deptId='data.formData.orgid' :Isstrictly="Isstrictly" />

      </template>
    </MOSTY.FromPage>
    <div v-if="AddShowfhqddia" class="dialog-box">
      <Addldfhqd v-if="AddShowfhqddia" :obj="rowObj" @onChange="onClose" />
    </div>

  </div>
</template>

<script setup>
import {
  reactive,
  ref,
  onMounted,
  getCurrentInstance,
  nextTick
} from "vue";
import * as MOSTY from "@/components/MyComponents/index";
import { getItem } from "@/utils/storage";
import Choosebm from "@/components/MyComponents/ChooseDept/index.vue";
import { getApi, postApi, uploadfilApi } from "@/api/tobAcco_api.js";
import Addldfhqd from "./Addldfhqd.vue";
import { ElMessage } from "element-plus";
import { downloadTemplate } from "@/utils/tools.js";
const fileBtn = ref()
const { proxy } = getCurrentInstance();
const { D_BZ_WPDW } = proxy.$dict("D_BZ_WPDW");
const props = defineProps({
  obj: {
    type: Object,
    default: () => { }
  }
});
const rules = reactive({
  orgname: [{ required: true, message: "单位不能为空", trigger: "blur" }],
  deptname: [{ required: true, message: "部门不能为空", trigger: "blur" }],
  time: [{ required: true, message: "发放日期不能为空", trigger: "blur" }],
  // ...rule.intRule({ validator: true, require: true }, "countnumber"),
  content: [{ required: true, message: "发放防护用品内容不能为空", trigger: "blur" }]
});
const AddShowfhqddia = ref(false)
const listQuery = ref({
  pageCurrent: 1,
  pageSize: 5

})
const rowObj = ref(
  {
    title: '劳动防护用品新增',
    saveBtn: true,
    labourId: null,
    id: null,
  }
)
const tableloading = ref(false)
const pageConfiger = ref({
  pageSize: 5,
  pageCurrent: 1,
  total: 0
})
const tableData = ref([])
const tabColumns = reactive([
  {
    title: "防护用品名称",
    prop: "name"
  },
  {
    title: "型号",
    prop: "model"
  },
  {
    title: "数量",
    prop: "count"
  },
  {
    title: "计量单位",
    prop: "unit",
    slot: true
  },
  {
    title: "领取人",
    prop: "person"
  },
  {
    title: "领取人岗位",
    prop: "position"
  },
  {
    title: "操作",
    prop: "actions",
    slot: true
  }
])
const Isstrictly = ref(false)
const showDept = ref(false)
const delrow = ref({});
const saveBtn = ref(false);
const loadingshow = ref(false);
const emit = defineEmits("onChange");
const ruleFormRef = ref();
const pageTitle = ref("");
const data = reactive({
  formData: {}
});

onMounted(() => {
  data.formData.orgname = getItem("deptId").ssdwmc
  data.formData.orgid = getItem("deptId").ssdwid
  pageTitle.value = props.obj.title;
  saveBtn.value = props.obj.saveBtn;
  if (props.obj.id) {
    gtdataxq(props.obj.id)

  }
});
//获取子表
function getqdzbData() {
  tableloading.value = true;

  getApi(
    listQuery.value,
    "/mosty-jcgl/labourGoodsAtta/getPageList"
  ).then((res) => {
    if (res.records) {
      tableloading.value = false;
      tableData.value = res.records;
      pageConfiger.value.total = res.total;
    } else {
      tableData.value = [];
      tableloading.value = false;
    }
  });
}
// 导入模板数据
const uploadFile = () => {
  nextTick(() => {
    fileBtn.value.click()
  })
}
// 获取文件
const changeFile = () => {
  nextTick(() => {
    let file = fileBtn.value.files[0]
    if (!file) { return; }
    let data = new FormData()
    data.append('file', file);
    data.append('labourId', listQuery.value.labourId);
    uploadfilApi(data, `/mosty-jcgl/labourGoodsAtta/batchUpload`).then(() => {
      ElMessage.success("批量上传成功");
      listQuery.pageCurrent = 1;
      getqdzbData()
    }).finally(() => {
      fileBtn.value.value = ''
    })
  })
}
//获取详情
function gtdataxq(id) {
  getApi({ id }, `/mosty-jcgl/labourGoods/getInfo`).then((res) => {
    data.formData = res
    listQuery.value.labourId = data.formData.id
    getqdzbData()
  });
}
function ChooesDdld() {
  showDept.value = true

}
function closezzjg(val) {
  showDept.value = false
}
function getSonValue(val) {
  data.formData.deptname = val.orgName
  data.formData.deptid = val.id
  showDept.value = false
}
function addypqd(type, id) {
  rowObj.value.labourId = data.formData.id
  if (type == 'add') {
    rowObj.value.title = '防护用品清单新增'
    rowObj.value.saveBtn = true
    rowObj.value.id = null
  } else if (type == 'exit') {
    rowObj.value.title = '防护用品清单修改'
    rowObj.value.saveBtn = true
    rowObj.value.id = id
  } else {
    rowObj.value.title = '防护用品清单详情'
    rowObj.value.saveBtn = false
    rowObj.value.id = id
  }
  AddShowfhqddia.value = true
}
function onClose() {
  AddShowfhqddia.value = false
  getqdzbData()
}
// 保存
const submit = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      loadingshow.value = true
      if (data.formData.id) {
        postApi(
          data.formData,
          "/mosty-jcgl/labourGoods/update"
        ).then((res) => {
          ElMessage.success("修改成功");
          emit("onChange", false);

        }).finally(() => {
          loadingshow.value = false
        });
      } else {
        postApi(
          data.formData,
          "/mosty-jcgl/labourGoods/add"
        ).then((res) => {
          ElMessage.success("新增成功");
          emit("onChange", false);
          loadingshow.value = false
        }).finally(() => {
          loadingshow.value = false
        });;
      }
    } else {
      ElMessage.warning('表单校验未通过！！！')
    }
  });
};
function delte(row) {
  postApi({}, `/mosty-jcgl/labourGoodsAtta/delete/${row.id}`).then(res => {
    ElMessage.success("删除成功");
    getqdzbData()
  })
}
const changeNo = (val) => {
  listQuery.value.pageCurrent = val;
  pageConfiger.value.pageCurrent = val;
  getqdzbData()
};
const changeSize = (val) => {
  listQuery.value.pageSize = val;
  pageConfiger.value.pageSize = val;
  getqdzbData()
};
const black = () => {
  if (saveBtn.value) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        // 关闭上一次的表单校验
        ruleFormRef.value.clearValidate();
        emit("onChange", false);
      })
      .catch(() => {
        // catch error
      })
  } else {
    // 关闭上一次的表单校验
    ruleFormRef.value.clearValidate();
    emit("onChange", false);
  }

};
</script>

<style lang="scss" scoped>
.eltabs4 {
  height: 40vh;
}

::-webkit-scrollbar {
  width: 0 !important;
  height: 0;
}

.box_cont {
  height: calc(100vh - 15vh);
  overflow-y: scroll;
}

.fromBox {
  width: 80%;
  margin: 20px auto;
  padding: 15px 15px 0 15px;
  border-radius: 1px;
}

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

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

.el-form-item {
  display: flex;
}

.addbtn {
  margin-bottom: 10px;
}

.bigBox {
  display: block !important;
  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>
