<template>
  <div class="bigBox" :style="{ height: bigHeight }">
    <MOSTY.FromPage :title="props.title" @closeDialog="black">
      <template #content>
        <MOSTY.Assort :title="'基本信息'" />
        <div class="fromBox" ref="fromBox">
          <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="grantname">
              <el-input v-model="data.fromObj.grantname" clearable style="width: 250px" />
            </el-form-item>
            <el-form-item label="领用时间:" prop="granttime">
              <el-date-picker v-model="data.fromObj.granttime" style="width: 250px" type="date"
                value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="领用人:" prop="useusername">
              <el-input v-model="data.fromObj.useusername" readonly style="width: 250px">
                <template #append>
                  <el-button class='cursor' @click="ChooesDdld('02')">选择</el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="领用部门:" prop="usedeptname">
              <el-input v-model="data.fromObj.usedeptname" clearable style="width: 250px" />
            </el-form-item>

            <el-form-item label="备注:">
              <el-input v-model="data.fromObj.bz" clearable style="width: 719px" />
            </el-form-item>
          </el-form>
        </div>
        <MOSTY.Assort :title="'发放物品列表'" />
        <div v-if='props.saveBtnShow'>
          <el-button class="addbtn" type="primary" @click="addInfo">
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>新增</span>
          </el-button>
        </div>
        <div class="tabbox">
          <el-table :data="data.fromObj.tbDangergoodsGrantChildList" border stripe style="width: 100%"
            :height="tableHeight" :key="keyCount" @row-click="handlecheckChange">
            <el-table-column prop="goodsname" align="center" label="物品名称">
            </el-table-column>
            <el-table-column prop="goodsmodel" label="物品型号">
            </el-table-column>
            <el-table-column prop="goodsspec" align="center" label="物品规格">
            </el-table-column>
            <el-table-column align="center" label="物品单位">
              <template #default="{ row }">
                <dict-tag :options="D_BZ_WPDW" :value="row.goodscompany" :tag="false" />
              </template>
            </el-table-column>
            <el-table-column prop="usenumber" align="center" label="领用数量">
            </el-table-column>
            <el-table-column prop="approvalname" align="center" label="批准人">
            </el-table-column>
            <el-table-column align="center" label="操作">
              <template #default="scope">
                <span v-if='!props.saveBtnShow' class="operate" style="color: yellowgreen"
                  @click="seeInfo(scope)">详情</span>
                <span v-if='props.saveBtnShow' class="operate" style="color: yellowgreen"
                  @click="editInfo(scope)">编辑</span>
                <span v-if='props.saveBtnShow' class="operate" style="color: yellowgreen"
                  @click="delInfo(scope.row)">删除</span>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </template>
      <template #footer>

        <el-button style="margin-left: 10px" v-loading='loadings' type="primary" @click="handleSave(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>

    <el-dialog v-model="dialogVisible" :title="data.title" width="50%" :before-close="handleClose" :inline="true"
      :rules="rules">
      <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="goodsname">
          <el-select v-model="fromObj.goodsname" style="width: 250px" @change="changewp" clearable
            placeholder="请选择物品名称：">
            <el-option v-for="item in wplist" :key="item" :label="item.goodsname" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="物品型号:" prop="goodsmodel">
          <el-input v-model="fromObj.goodsmodel" disabled clearable style="width: 250px" />
        </el-form-item>
        <el-form-item label="物品规格:" prop="goodsspec">
          <el-input v-model="fromObj.goodsspec" clearable disabled style="width: 250px" />
        </el-form-item>
        <el-form-item label="物品单位:" prop="goodscompany">
          <el-select v-model="fromObj.goodscompany" style="width: 250px" disabled clearable>
            <el-option v-for="item in D_BZ_WPDW" :key="item" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="库存数量:" prop="stocknumber" v-if="isAdd">
          <el-input v-model.number="fromObj.stocknumber" type='number' disabled clearable style="width: 250px" />
        </el-form-item>
        <el-form-item label="领用数量:" prop="usenumber">
          <el-input v-model.number="fromObj.usenumber" type='number' clearable @change="changenumber"
            style="width: 250px" />
        </el-form-item>
        <div class="ld_box">
          <el-form-item label="批准人:">
            <el-input v-model="fromObj.approvalname" style="width: 250px" readonly>
              <template #append>
                <el-button class='cursor' @click="ChooesDdld('01')">选择</el-button>
              </template>
            </el-input>
          </el-form-item>
        </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button type="primary" v-loading='loadingshow' @click="submitry(elform)" v-if="props.saveBtnShow">
            保存
          </el-button>
          <el-button @click="handleClose">取消</el-button>
        </span>
      </template>
    </el-dialog>

    <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :data="memberList" :deptId="data.deptId"
      :leaderid="leaderid" @choosedUsers="getSonValue"></ChooseUser>
  </div>
</template>

<script setup>
import {
  ref,
  onMounted,
  defineProps,
  defineEmits,
  reactive,
  watch,
  watchEffect,
  getCurrentInstance
} from "vue";
import { ElMessage } from "element-plus";
import * as MOSTY from "@/components/MyComponents/index";
import { getItem } from "@/utils/storage";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
import { getApi, deleteApi, putApi, postApi } from "@/api/tobAcco_api.js";
import * as rule from "@/utils/rules.js";
const { proxy } = getCurrentInstance();
const { D_BZ_WPDW } = proxy.$dict("D_BZ_WPDW");
// import Addaqry from "./addaqry.vue";
const props = defineProps({
  title: {
    type: String,
    default: ""
  },
  saveBtnShow: {
    type: Boolean,
    default: true
  },
  editObj: {
    type: Object,
    default: () => { }
  }
});
const loadingshow = ref(false)
const loadings = ref(false)
const rules = reactive({
  grantname: [{ required: true, message: "发放名称不能为空", trigger: "blur" }],
  granttime: [{ required: true, message: "领用时间不能为空", trigger: "blur" }],
  useusername: [{ required: true, message: "领用人不能为空", trigger: "blur" }],
  usedeptname: [
    { required: true, message: "领用部门不能为空", trigger: "blur" }
  ]
});
const rules2 = reactive({
  goodsname: [{ required: true, message: "物品名称不能为空", trigger: "blur" }],
  goodsmodel: [
    { required: true, message: "物品型号不能为空", trigger: "blur" }
  ],
  goodsspec: [{ required: true, message: "物品规格不能为空", trigger: "blur" }],
  goodscompany: [
    { required: true, message: "物品单位不能为空", trigger: "blur" }
  ],
  ...rule.intRule({ validator: true, require: false, message: "库存为0，不能发放" }, "stocknumber"),
  ...rule.intRule({ validator: true, require: true }, "usenumber"),

});
const activeNames = ref(1);
const emits = defineEmits(["close"]);
const chooseUserVisible = ref(false); //选择领导弹窗
const singleShow = ref(true); //单选多选
const leaderid = ref("");
const fromObj = ref({});
const zzlx = ref(null);
const isAdd = ref(false)
const CloseEvent = () => {
  if (props.saveBtnShow) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        // 关闭上一次的表单校验
        ruleFormRef.value.clearValidate();
        emits("close");
      })
      .catch(() => {
        // catch error
      })
  } else {
    // 关闭上一次的表单校验
    ruleFormRef.value.clearValidate();
    emits("close");
  }

};
const data = reactive({
  fromObj: {}
});
//限制选人只能为本部门的人
function getdeptId() {
  data.deptId = getItem("deptId").ssbmid;
}
onMounted(() => {
  activeNames.value = ["1"];
  getdeptId();
});
//点击带队领导选择按钮
function ChooesDdld(val) {
  zzlx.value = val;
  leaderid.value = "";
  if (val == "01") {
    leaderid.value = fromObj.value.approval;
    singleShow.value = true;
    chooseUserVisible.value = true;
  }
  if (val == "02") {
    leaderid.value = data.fromObj.useuserid;
    singleShow.value = true;
    chooseUserVisible.value = true;
  }
}
const getSonValue = (value) => {
  if (zzlx.value == "01") {
    fromObj.value.approvalname = value[0].userName;
    fromObj.value.approval = value[0].id;
  }
  if (zzlx.value == "02") {
    data.fromObj.useusername = value[0].userName;
    data.fromObj.useuserid = value[0].id;
    data.fromObj.usedeptname = value[0].deptName;
    data.fromObj.usedeptcode = value[0].deptId;
  }
};
//选择物品
const wplist = ref([]);
function getwplist() {
  getApi(
    {},
    "/mosty-jcgl/dangergoodsPurchaseChild/queryDangergoodsByOrgcode"
  ).then((res) => {
    if (res) {
      wplist.value = res;
    }
  });
}
//选择物品
const changewp = (val) => {
  fromObj.value.goodsid = val;
  wplist.value.forEach((item) => {
    if (item.id == val) {
      fromObj.value.goodsmodel = item.goodsmodel;
      fromObj.value.goodsspec = item.goodsspec;
      fromObj.value.goodscompany = item.goodscompany;
      fromObj.value.stocknumber = item.goodsnumber;
      fromObj.value.goodsname = item.goodsname;
    }
  });
};
//输入领用数量
const changenumber = (val) => {
  if (fromObj.value.stocknumber) {
    if (Number(val) > Number(fromObj.value.stocknumber)) {
      ElMessage.error("领用数量需要小于库存数量");
      fromObj.value.usenumber = 0;
    }
  }
};
const dialogVisible = ref(false);
//新增
function addInfo() {
  fromObj.value = {};
  dialogVisible.value = true;
  getwplist();
  data.title = "发放物品新增";
  isAdd.value = true
}
const current = ref();
//修改
function editInfo(row) {
  getwplist();
  current.value = row.$index;
  fromObj.value = row.row;
  dialogVisible.value = true;
  data.title = "发放物品修改";
  isAdd.value = false
}
//查看 
function seeInfo(row) {
  getwplist();
  current.value = row.$index;
  fromObj.value = row.row;
  dialogVisible.value = true;
  data.title = "发放物品详情";
  isAdd.value = false
}
//删除
function delInfo(row) {
  data.fromObj.tbDangergoodsGrantChildList.forEach((item, index) => {
    if (row == item) {
      data.fromObj.tbDangergoodsGrantChildList.splice(index, 1);
    }
  });
}
const elform = ref();
//新增修改完毕
const submitry = async (elform) => {
  if (!elform) return;
  await elform.validate((valid) => {
    if (valid) {

      if (Number(fromObj.value.usenumber) > Number(fromObj.value.stocknumber)) {
        ElMessage.error("领用数量需要小于库存数量");
      } else {

        if (Number(fromObj.value.usenumber) > 0) {
          loadingshow.value = true
          if (data.title == "发放物品新增") {
            if (data.fromObj.tbDangergoodsGrantChildList) {
              data.fromObj.tbDangergoodsGrantChildList.push(fromObj.value);
              dialogVisible.value = false;
              wplist.value = [];
              loadingshow.value = false
            } else {
              let arr = [];
              arr.push(fromObj.value);
              data.fromObj.tbDangergoodsGrantChildList = arr;
              dialogVisible.value = false;
              wplist.value = [];
              loadingshow.value = false
            }
          }
          if (data.title == "发放物品修改") {
            data.fromObj.tbDangergoodsGrantChildList[current.value] = fromObj.value;
            dialogVisible.value = false;
            wplist.value = [];
            loadingshow.value = false
          }
        }
      }

    } else {
      ElMessage.error("表单验证失败，请检查输入内容");
    }
  });
};
watchEffect(() => {
  if (props.editObj) {
    data.fromObj = props.editObj;
    data.fromObj.tbDangergoodsGrantChildList = data.fromObj
      .tbFireControlRoomChildList
      ? data.fromObj.tbDangergoodsGrantChildList
      : [];
  } else {
    data.fromObj = {};
    data.fromObj.tbDangergoodsGrantChildList = [];
  }
});
const ruleFormRef = ref();
// 保存
const handleSave = async (ruleFormRef) => {
  if (!ruleFormRef) return;
  await ruleFormRef.validate((valid) => {
    if (valid) {
      loadings.value = true
      if (data.fromObj) {
        if (data.fromObj.tbDangergoodsGrantChildList.length) {
          if (!data.fromObj.id) {
            postApi(
              data.fromObj,
              "/mosty-jcgl/dangergoodsGrant/addDangergoodsGrantOne"
            )
              .then((res) => {
                ElMessage.success("新增成功");
                emits("close");
                loadings.value = false
              })
              .catch((err) => {
                loadings.value = false
              });
          } else {
            postApi(
              data.fromObj,
              "/mosty-jcgl/dangergoodsGrant/updateDangergoodsGrantOne"
            )
              .then((res) => {
                ElMessage.success("修改成功");
                emits("close");
                loadings.value = false
              })
              .catch((err) => {
                loadings.value = false
              });
          }
        } else {
          ElMessage.error("请填写发放物品表");
        }
      }
    } else {
      ElMessage.error("请输入必填项");
    }
  });
};
function handleClose(params) {
  if (props.saveBtnShow) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        dialogVisible.value = false
      })
      .catch(() => {
        // catch error
      })
  } else {
    dialogVisible.value = false
  }

}
</script>

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

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

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

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

.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>