<template>
  <div class="bigBox" :style="{ height: bigHeight }">
    <MOSTY.FromPage :title="data.config.title" @closeDialog="black">
      <template #content>
        <div class="box_cont">
          <div class="fromBoxs">
            <el-form class="mosty-from-wrap" ref="ruleFormRef" label-width="135px" :model="data.formData" :inline="true"
              :rules="rules" :disabled="!data.config.saveBtnShow">
              <!-- <el-form-item label="预案名称" prop="planname" @click="yaShow = true">
                <el-input v-model="data.formData.planname" placeholder="请输入预案名称" readonly
                  style="width: 250px"></el-input>
              </el-form-item> -->
              <el-form-item label="记录单位">
                <el-input v-model="data.formData.inputcomname" disabled placeholder="请输入记录单位"
                  style="width: 250px"></el-input>
              </el-form-item>
              <el-form-item label="记录部门">
                <el-input v-model="data.formData.inputdepname" placeholder="请输入记录部门" disabled
                  style="width: 250px"></el-input>
              </el-form-item>
              <el-form-item label="记录人">
                <el-input v-model="data.formData.inputpeoname" disabled placeholder="请选择记录人"
                  style="width: 250px"></el-input>
              </el-form-item>
              <el-form-item label="类别" prop="emcategory">
                <el-select v-model="data.formData.emcategory" placeholder="请选择类别" style="width: 250px">
                  <el-option v-for="item in D_TB_YJWZLB" :key="item.value" :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="名称" prop="emname">
                <el-input v-model="data.formData.emname" placeholder="请输入名称" clearable style="width: 250px"></el-input>
              </el-form-item>
              <!-- <el-form-item label="规格型号" prop="emspeamod">
                <el-input v-model="data.formData.emspeamod" placeholder="规格型号" maxlength="11" clearable
                  style="width: 250px"></el-input>
              </el-form-item> -->
              <el-form-item label="数量" prop="emcount">
                <el-input v-model="data.formData.emcount" placeholder="请输入数量" clearable style="width: 250px"
                  maxlength="11" type="number"></el-input>
              </el-form-item>
              <el-form-item label="责任人" prop="responsperson">
                <el-input v-model="data.formData.responsperson" placeholder="请输入责任人" readonly style="width: 250px"
                  @click="ChooesDdld('01')"></el-input>
              </el-form-item>
              <el-form-item label="责任人联系电话" prop="responsperphe">
                <MOSTY.Phone width="250px" show-word-limit v-model="data.formData.responsperphe" maxlength="11"
                  clearable @onInput="phoneChange">
                </MOSTY.Phone>
              </el-form-item>
              <el-form-item label="生产时间:" prop="productionDate">
                <el-date-picker style="width: 250px" v-model="data.formData.productionDate" type="date"
                  value-format="YYYY-MM-DD" placeholder="请选择资源物资生产时间" @change="timeChange" />
              </el-form-item>
              <el-form-item label="过期时间:" prop="expirationDate">
                <el-date-picker style="width: 250px" v-model="data.formData.expirationDate" type="date"
                  value-format="YYYY-MM-DD" placeholder="请选择资源物资过期时间" @change="timeChange" />
              </el-form-item>
              <!-- <el-form-item label="用途" prop="emuses">
                <el-select v-model="data.formData.emuses" placeholder="请选择用途" style="width: 250px">
                  <el-option v-for="item in D_TB_YJWZYT" :key="item.value" :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
              </el-form-item> -->
              <!-- <el-form-item label="单位" prop="unit">
                <el-select v-model="data.formData.unit" placeholder="请选择单位" style="width: 250px">
                  <el-option v-for="item in D_BZ_WPDW" :key="item.value" :label="item.label"
                    :value="item.value"></el-option>
                </el-select>
              </el-form-item> -->
              <el-form-item label="存放部位" prop="placename">
                <el-cascader style="width: 500px" class="el-cascader-zj" :show-all-levels="true" placeholder='请选择部位名称：'
                  :options="csmcList" v-model="scenePath" :props="cascaderProps" clearable
                  @change="handleSelectStatus" />
              </el-form-item>
              <!-- <el-form-item label="使用条件" prop="conditionsofuse">
                <el-input v-model="data.formData.conditionsofuse" placeholder="请输入使用条件" clearable
                  style="width: 250px"></el-input>
              </el-form-item> -->
              <el-form-item label="具体位置" prop="emstorage">
                <el-input v-model="data.formData.emstorage" placeholder="请输入具体位置" clearable
                  style="width: 500px"></el-input>
              </el-form-item>
              <el-form-item label="备注" prop="bz" style="width: 100%">
                <el-input v-model="data.formData.bz" type="textarea" show-word-limit maxlength="200"
                  style="width: 100%" />
              </el-form-item>
            </el-form>
          </div>
        </div>
      </template>
      <template #footer>
        <el-button @click="black"><el-icon>
            <DocumentDelete />
          </el-icon>关闭</el-button>
        <el-button type="primary" @click="submit(ruleFormRef)" v-if="data.config.saveBtnShow"><el-icon>
            <DocumentChecked />
          </el-icon>保存</el-button>

      </template>
    </MOSTY.FromPage>


    <!-- 选择用户 -->
    <ChooseUser v-model="chooseUserVisible" :Single="singleShow" :leaderid="leaderid" @choosedUsers="getSonValue"
      :deptId="filterqx('isaqbm') == '1' ? getItem('deptId').ssdwid : data.deptId"></ChooseUser>
    <!-- 选择预案 -->
    <el-dialog v-model="yaShow" title="选择预案" width="1000px" :show-close="false">
      <el-table ref="multipleTableRef" stripe v-loading="yaLoading" :data="yaList" style="width: 100%" border>
        <el-table-column width="55" #default="{ row }">
          <el-radio v-model="radioIndex" :label="row.id"></el-radio>
        </el-table-column>
        <el-table-column label="所属单位" show-overflow-tooltip property="orgname"></el-table-column>
        <el-table-column label="预案名称" show-overflow-tooltip property="planname"></el-table-column>
        <el-table-column label="预案类型" show-overflow-tooltip property="plantype">
          <template #default="{ row }">
            <dict-tag :options="D_TB_YALX" :value="row.plantype" :tag="false" />
          </template>
        </el-table-column>
      </el-table>
      <div style="margin-top: 10px">
        <el-pagination class="pagination" @current-change="handleCurrentChange" :current-page="listQuery.pageCurrent"
          :page-size="listQuery.pageSize" layout="total, prev, pager, next, jumper" :total="yaTotal"></el-pagination>
      </div>
      <template #footer>
        <span class="dialog-footer">

          <el-button type="primary" @click="submitYa">确定</el-button>
          <el-button type="warning" @click="
            yaShow = false;
          radioIndex = null;
          ">取消</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref, watchEffect, getCurrentInstance, onMounted } from "vue";
import { getApi, postApi } from "@/api/tobAcco_api.js";
import { getItem } from "@/utils/storage";
import { filterqx } from "@/utils/auth.js"
import * as rule from "@/utils/rules.js";
import * as MOSTY from "@/components/MyComponents/index";
import ChooseUser from "@/components/MyComponents/ChooseUser/Leader.vue";
const { proxy } = getCurrentInstance();
import { ElMessage } from "element-plus";
const { D_TB_YJWZLB, D_TB_YJWZYT, D_BZ_WPDW, D_TB_YALX } = proxy.$dict(
  "D_TB_YJWZLB",
  "D_TB_YJWZYT",
  "D_BZ_WPDW",
  "D_TB_YALX"
);
const props = defineProps({
  saveBtnShow: {
    type: Boolean,
    default: true
  },
  editObj: {
    type: Object,
    default: () => { }
  }
});
const emit = defineEmits("changePage");
const ruleFormRef = ref();
const yaShow = ref(false);
const yaLoading = ref(false);
const radioIndex = ref(null);
const data = reactive({
  formData: {},
  extendattr: {},
  config: {
    title: "",
    saveBtnShow: true,
    wbjlShow: false,
    jcrzShow: false
  }
});
const yaTotal = ref(0);
const yaList = ref([]);
const listQuery = reactive({
  pageCurrent: 1,
  pageSize: 10
});
const csmcList = ref([]); //场所名称

onMounted(() => {
  if (props.editObj) {
    data.config = JSON.parse(JSON.stringify(props.editObj));
  }
  getMain(props.editObj.id);
  getName();
  getCsData();
  // 获取预案信息列表
  getYaPage();
});
//点击带队领导选择按钮
const chooseUserVisible = ref(false); //选择领导弹窗
const singleShow = ref(true); //单选多选
const leaderid = ref("");
const zzlx = ref(null);
//点击带队领导选择按钮
function ChooesDdld(val) {
  zzlx.value = val;
  leaderid.value = "";
  if (val == "01") {
    leaderid.value = data.formData.responsperid;
    singleShow.value = true;
    chooseUserVisible.value = true;
  }
}
const getSonValue = (value) => {
  if (zzlx.value == "01") {
    data.formData.responsperson = value[0].userName;
    data.formData.responsperid = value[0].id;
  }
};
const rules = reactive({
  ...rule.phoneRule({
    require: true,
    validator: true
  }, 'responsperphe'),
  productionDate: [{ required: true, message: "资源物资生产时间不能为空", trigger: "blur" }],
  expirationDate: [{ required: true, message: "资源物资过期时间不能为空", trigger: "blur" }],
  emcategory: [{ required: true, message: "请选择类别", trigger: "change" }],
  emuses: [
    {
      required: true,
      message: "请选择用途",
      trigger: "change"
    }
  ],
  planname: [
    {
      required: true,
      message: "请选择存放部位",
      trigger: "blur"
    }
  ],
  emname: [
    {
      required: true,
      message: "请输入名称",
      trigger: "input"
    }
  ],
  emspeamod: [
    {
      required: true,
      message: "请输入规格型号",
      trigger: "blur"
    }
  ],
  ...rule.intRule({ validator: true, require: true }, "emcount"),
  responsperson: [
    {
      required: true,
      message: "请输入责任人",
      trigger: "blur"
    }
  ],
  placename: [
    {
      required: true,
      message: "请输入具体位置",
      trigger: "blur"
    }
  ],
  conditionsofuse: [
    {
      required: true,
      message: "请输入使用条件",
      trigger: "blur"
    }
  ],
  emstorage: [
    {
      required: true,
      message: "请输入存放点",
      trigger: "blur"
    }
  ],
  unit: [
    {
      required: true,
      message: "请选择单位",
      trigger: "blur"
    }
  ]
});

// 确认预案
const submitYa = () => {
  data.formData.planid = radioIndex.value;
  yaList.value.forEach((ya) => {
    if (ya.id == radioIndex.value) {
      data.formData.planname = ya.planname;
    }
  });
  yaShow.value = false;
};
// 却换页码
const handleCurrentChange = (val) => {
  listQuery.pageCurrent = val;
  getYaPage();
};
// 获取预案信息列表
const getYaPage = () => {
  yaLoading.value = true;
  getApi(listQuery, "/mosty-jcgl/yabz/queryYabzByOrgcode").then((res) => {
    if (res) {
      yaTotal.value = res.total;
      yaList.value = res.records;
    }
    yaLoading.value = false;
  });
};
// 保存
const submit = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid) => {
    if (valid) {
      if (data.formData.id) {
        postApi(
          data.formData,
          "/mosty-jcgl/emergencysupplies/updateEmergencysuppliesOne"
        ).then(() => {
          ElMessage.success("修改成功");
          emit("changePage", "Main");
        });
      } else {
        postApi(
          data.formData,
          "/mosty-jcgl/emergencysupplies/addEmergencysuppliesOne"
        ).then(() => {
          ElMessage.success("新增成功");
          emit("changePage", "Main");
        });
      }
    }
  });
};
//获取详情
function getMain(id) {
  data.deptId = getItem("deptId").ssbmid;
  if (id) {
    getApi(
      { id: id },
      "/mosty-jcgl/emergencysupplies/queryEmergencysuppliesById"
    ).then((res) => {
      if (res) {
        data.formData = res;
        scenePath.value = res.scenePath.split('-')
        console.log(res.scenePath, 'scenePath')
        console.log(scenePath.value, 'scenePath')
        radioIndex.value = res.placeid;
        if (res.planid) {
          getApi({ id: res.planid }, "/mosty-jcgl/yabz/queryYabzById").then((res) => {
            if (res) {
              data.formData.planname = res.planname
            }
          });
        }

      }
    });
  }
}

const black = () => {
  if (data.config.saveBtnShow) {
    proxy.$modal.confirm('离开会丢失页面中修改的内容，确认离开吗？')
      .then(() => {
        emit("changePage", "Main");
      })
      .catch(() => {
        // catch error
      })
  } else {
    emit("changePage", "Main");
  }

};
function getName() {
  if (data.config.title == "新增应急资源") {
    data.formData.inputpeoname = getItem("USERNAME");
    data.formData.inputpeoid = getItem("USERID");
    data.formData.inputdepid = getItem("deptId").ssbmid;
    data.formData.inputdepname = getItem("deptId").ssbmmc;
    data.formData.inputcomid = getItem("deptId").ssdwid;
    data.formData.inputcomname = getItem("deptId").ssdwmc;
  }
}
//根据操作人 查询 部位
function getCsData() {
  getApi({}, "/mosty-jcgl/site/queryAllSceneTree").then((res) => {
    csmcList.value = res;
  });
}
// 部位选择
const cascaderProps = {
  value: 'id',
  label: 'name',
  children: 'children'
}
// 具体位置
const scenePath = ref([])
const scenePathName = ref('')
// 获取完整选中信息的版本
const handleSelectStatus = (value) => {
  let selectedData = []
  if (value && value.length > 0) {
    let currentOptions = csmcList.value
    data.formData.emstorage = ''
    value.forEach((id, index) => {
      const option = currentOptions.find(opt => opt.id === id)
      if (option) {
        selectedData.push({
          id: option.id,
          name: option.name,
          type: option.type,
          scenePath: option.scenePath,
          level: index + 1
        })
        data.formData.emstorage += option.name + ''
        currentOptions = option.children || []
      }
    })
    data.formData.scenePath = selectedData[selectedData.length - 1].scenePath
    data.formData.placename = selectedData[selectedData.length - 1].name
    data.formData.placeid = selectedData[selectedData.length - 1].id;
  }
}
//获取场所选择
const changeCsmc = (val) => {
  csmcList.value.forEach((item) => {
    if (item.id == val) {
      data.formData.placeid = item.id;
      data.formData.placename = item.placename;
    }
  });
};

</script>

<style lang="scss" scoped>
::v-deep .el-radio__label {
  display: none !important;
}

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

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

.fromBoxs {
  width: 100%;
  margin: 20px auto;
}

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

.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: 250px;
  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-radio__label {
  display: none;
}
</style>
