<template>
  <div class="bigBox" :style="{ height: bigHeight }">
    <MOSTY.FromPage :title="props.title" @closeDialog="CloseEvent">
      <template #content>
        <MOSTY.Assort :title="'基本信息'" />
        <div class="fromBox">
          <el-form class="mosty-from-wrap" ref="ruleFormRef" label-width="130px" :model="data.fromObj" :inline="true"
            :rules="rules" :disabled='!saveBtnShow'>
            <el-form-item label="采购名称:" prop="purchasename">
              <el-input v-model="data.fromObj.purchasename" clearable style="width: 250px" />
            </el-form-item>
            <el-form-item label="采购时间:" prop="purchasetime">
              <el-date-picker v-model="data.fromObj.purchasetime" style="width: 250px" type="date"
                value-format="YYYY-MM-DD" />
            </el-form-item>
            <el-form-item label="采购人:" prop="purchaseusername">
              <el-input v-model="data.fromObj.purchaseusername" readonly style="width: 250px">
                <template #append>
                  <el-button class='cursor' @click="ChooesDdld">选择</el-button>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="采购部门:" prop="purchasedeptname">
              <el-input v-model="data.fromObj.purchasedeptname" readonly style="width: 250px" />
            </el-form-item>

            <el-form-item label="备注:" style="width: 100%;">
              <el-input v-model="data.fromObj.bz" autosize clearable style="width: 100%" />
            </el-form-item>
          </el-form>
        </div>
        <MOSTY.Assort :title="'采购物品列表'" />
        <div v-if='saveBtnShow'>
          <el-button class="addbtn" type="primary" @click="addShowinput">
            <el-icon>
              <CirclePlus />
            </el-icon>
            <span>新增</span>
          </el-button>
          <el-button class="addbtn" type="primary" @click="submittab">
            <el-icon>
              <Select />
            </el-icon>
            <span>保存</span>
          </el-button>

        </div>
        <div class="tabbox">
          <el-table :data="data.fromObj.tbDangergoodsPurchaseChildList" border stripe style="width: 100%"
            :height="tableHeight" :key="keyCount" @row-click="handlecheckChange">
            <el-table-column prop="goodsname" align="center" label="物品名称">
              <template #default="{ row }">
                <input v-if="row.input == true" type="text" v-model="row.goodsname" />
                <span v-else>{{ row.goodsname }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="goodsmodel" label="物品型号">
              <template #default="{ row }">
                <input v-if="row.input == true" type="text" v-model="row.goodsmodel" />
                <span v-else>{{ row.goodsmodel }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="goodsspec" align="center" label="物品规格">
              <template #default="{ row }">
                <input v-if="row.input == true" type="text" v-model="row.goodsspec" />
                <span v-else>{{ row.goodsspec }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="goodsnumber" align="center" label="物品数量">
              <template #default="{ row }">
                <el-input-number v-if="row.input == true" v-model="row.goodsnumber" :min="0" :max="999999"
                  controls-position="right" />
                <span v-else>{{ row.goodsnumber }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="goodscompany" align="center" label="物品单位">
              <template #default="{ row }">
                <el-select v-if="row.input == true" v-model="row.goodscompany" style="width: 100%" clearable
                  placeholder="请选择单位：">
                  <el-option v-for="item in D_BZ_WPDW" :key="item" :label="item.label" :value="item.value" />
                </el-select>
                <dict-tag v-else :options="D_BZ_WPDW" :value="row.goodscompany" :tag="false" />
              </template>
            </el-table-column>
            <el-table-column prop="bz" align="center" label="备注">
              <template #default="{ row }">
                <input v-if="row.input == true" type="text" v-model="row.bz" />
                <span v-else>{{ row.bz }}</span>
              </template>
            </el-table-column>
            <el-table-column align="center" label="操作" v-if='saveBtnShow'>
              <template #default="{ row }">
                <el-button class="addbtn" type="primary" @click="deletetab(row)">
                  <el-icon>
                    <DeleteFilled />
                  </el-icon>
                  <span>删除</span>
                </el-button>
              </template>
            </el-table-column>

          </el-table>
        </div>

      </template>
      <template #footer>

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

    <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :data="null" :leaderid="leaderid" :deptId="null"
      @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";
const { proxy } = getCurrentInstance();
const { D_BZ_SBSSZT, D_BZ_WPDW, D_TB_JCBZLB, D_BZ_JXSBLX, D_BZ_JCZT } =
  proxy.$dict(
    "D_BZ_SBSSZT",
    "D_BZ_WPDW",
    "D_TB_JCBZLB",
    "D_BZ_JXSBLX",
    "D_BZ_JCZT"
  );
// import Addaqry from "./addaqry.vue";
const props = defineProps({
  title: {
    type: String,
    default: ""
  },
  saveBtnShow: {
    type: Boolean,
    default: true
  },
  rowid: {
    type: String,
    default: null
  }
});
const rules = reactive({
  purchasename: [
    { required: true, message: "采购名称不能为空", trigger: "blur" }
  ],
  purchasetime: [
    { required: true, message: "采购时间不能为空", trigger: "blur" }
  ],
  purchaseusername: [
    { required: true, message: "采购人不能为空", trigger: "blur" }
  ],
  purchasedeptname: [
    { required: true, message: "采购部门不能为空", trigger: "blur" }
  ]
});
const emits = defineEmits(["close"]);
const currentRow = ref(); //选中的表格数据
const currentRowjc = ref(); //选中的表格数据
const chooseUserVisible = ref(false); //选择领导弹窗
const singleShow = ref(true); //单选多选
const leaderid = ref("");
const loadingshow = ref(false)
const zzlx = ref(null);

const ruleFormRef = ref();
const CloseEvent = () => {
  if (props.saveBtnShow) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        // 关闭上一次的表单校验
        ruleFormRef.value.clearValidate();
        emits("close");
      })
      .catch(() => {
        // catch error
      })
  } else {
    // 关闭上一次的表单校验
    ruleFormRef.value.clearValidate();
    emits("close");
  }

};
onMounted(() => {
  if (props.rowid) {
    getmain(props.rowid)
  } else {
    data.fromObj = {};
    data.fromObj.tbDangergoodsPurchaseChildList = [];
  }
});
const data = reactive({
  fromObj: {
    tbDangergoodsPurchaseChildList: []
  }
});
//详情
const getmain = (id) => {
  if (id) {
    getApi({}, "/mosty-jcgl/dangergoodsPurchase/getDangergoodsPurchaseById/" + 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(",");
          }
        }
        getApi(
          { id: id },
          "/mosty-jcgl/dangergoodsPurchaseChild/queryDangergoodsPurchaseChildById"
        ).then((res) => {
          if (res) {
            data.fromObj.tbDangergoodsPurchaseChildList = res ? res : [];
          }
        });
      }

    });

  }
};
//点击带队领导选择按钮
function ChooesDdld() {
  leaderid.value = data.fromObj.purchaseuserid;
  singleShow.value = true;
  chooseUserVisible.value = true;
}
const getSonValue = (value) => {
  data.fromObj.purchaseusername = value[0].userName;
  data.fromObj.purchaseuserid = value[0].id;
  data.fromObj.purchasedeptcode = value[0].deptId;
  data.fromObj.purchasedeptname = value[0].deptName;

};
//新增表格
function addShowinput() {
  let tab = {
    goodsname: "",
    goodsmodel: "",
    goodsspec: "",
    goodsnumber: "",
    goodscompany: "",
    bz: "",
    input: true
  };
  if (data.fromObj.tbDangergoodsPurchaseChildList && data.fromObj.tbDangergoodsPurchaseChildList.length) {
    if (data.goodsname != "" && data.goodsmodel != "") {
      data.fromObj.tbDangergoodsPurchaseChildList.push(tab);
    }
  } else {
    data.fromObj.tbDangergoodsPurchaseChildList.push(tab);
  }
}
//保存表格数据
function submittab() {
  data.fromObj.tbDangergoodsPurchaseChildList.forEach((el) => {
    el.input = false;
  });
}
//删除表格数据
function deletetab(row) {
  data.fromObj.tbDangergoodsPurchaseChildList.forEach((item, index) => {
    if (row == item) {
      data.fromObj.tbDangergoodsPurchaseChildList.splice(index, 1);
    }
  });
}
//选中当前表格行
function handlecheckChange(val) {
  if (props.saveBtnShow) {
    currentRowjc.value = val;
    data.fromObj.tbDangergoodsPurchaseChildList.forEach((el) => {
      if (el == val) {
        el.input = true;
      }
    });
  }

}

// 保存
const handleSave = async (ruleFormRef) => {
  if (!ruleFormRef) return;
  await ruleFormRef.validate((valid) => {
    if (valid) {
      loadingshow.value = true
      if (data.fromObj) {
        if (data.fromObj.tbDangergoodsPurchaseChildList.length) {
          if (!data.fromObj.id) {
            postApi(data.fromObj, "/mosty-jcgl/dangergoodsPurchase/addDangergoodsPurchaseOne").then((res) => {
              ElMessage.success("新增成功");
              emits("close");
              loadingshow.value = false
            }).catch((err) => {
              loadingshow.value = false
            });
          } else {
            postApi(data.fromObj, "/mosty-jcgl/dangergoodsPurchase/updateDangergoodsPurchaseOne").then((res) => {
              ElMessage.success("修改成功，请前往发放页面修改数据，以确保数据准备性！！");
              emits("close");
              loadingshow.value = false
            }).catch((err) => {
              loadingshow.value = false
            });
          }
        } else {
          ElMessage.error("请填写采购物品表");
          loadingshow.value = false
        }
      }
    } else {
      ElMessage.error("请输入必填项");
      loadingshow.value = false
    }
  });
};
</script>

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

.fromBox {
  width: 100%;
  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>