<template>
  <u-popup
    :show="visible"
    mode="bottom"
    :round="10"
    :closeOnClickOverlay="false"
    @close="cancel"
    class="accident-popup"
  >
    <view class="popup-content">
      <view class="popup-header"
        ><text class="popup-title">{{ dialogTitle }}</text
        ><view class="close-btn" @click="cancel">×</view></view
      >
      <scroll-view class="popup-body" scroll-y>
        <view class="card-a">
          <!-- 事故事件信息 -->
          <view class="card-section">
            <view class="section-title">📋 事故事件信息</view>
            <u--form
              labelPosition="left"
              labelWidth="180rpx"
              :model="form"
              :rules="rules"
              ref="formRef"
            >
              <u-form-item
                label="事故事件名称"
                prop="acdntName"
                borderBottom
                required
              >
                <u--input
                  v-model="form.acdntName"
                  placeholder="请输入"
                  :disabled="isView"
                  border="none"
                  inputAlign="right"
                />
              </u-form-item>
              <u-form-item
                label="发生时间"
                prop="occurrenceTime"
                borderBottom
                required
              >
                <view
                  class="picker-value"
                  @click="!isView && showDateTimePicker('occurrenceTime')"
                  >{{ form.occurrenceTime || "请选择" }}</view
                >
                <u-icon slot="right" name="arrow-right" />
              </u-form-item>
              <u-form-item
                label="事故发生地点"
                prop="acdntPlace"
                borderBottom
                required
              >
                <u--input
                  v-model="form.acdntPlace"
                  placeholder="请输入"
                  :disabled="isView"
                  border="none"
                  inputAlign="right"
                />
              </u-form-item>
              <u-form-item label="来源类型" borderBottom>
                <view
                  class="picker-value"
                  @click="!isView && showSourceTypePicker()"
                  >{{ getSourceTypeLabel(form.sourceType) || "请选择" }}</view
                >
                <u-icon slot="right" name="arrow-right" />
              </u-form-item>
              <u-form-item label="来源单据名称" borderBottom>
                <u--input
                  v-model="form.sourceName"
                  placeholder="请选择"
                  readonly
                  :disabled="isView"
                  border="none"
                  inputAlign="right"
                  @click="addSource"
                />
              </u-form-item>
              <u-form-item
                label="事故事件经过"
                prop="acdntPass"
                borderBottom
                required
              >
                <u--textarea
                  v-model="form.acdntPass"
                  placeholder="请输入"
                  :disabled="isView"
                  border="none"
                  height="120rpx"
                />
              </u-form-item>
              <u-form-item label="上报人" prop="reportPersonName" borderBottom>
                <u--input
                  v-model="form.reportPersonName"
                  placeholder="请选择"
                  readonly
                  :disabled="isView"
                  border="none"
                  inputAlign="report"
                  @click="userOpen('duty')"
                />
              </u-form-item>
              <u-form-item label="上报部门" borderBottom>
                <u--input
                  v-model="form.reportDeptName"
                  disabled
                  border="none"
                  inputAlign="right"
                />
              </u-form-item>
              <u-form-item
                label="上报时间"
                prop="reportTime"
                borderBottom
                required
              >
                <view
                  class="picker-value"
                  @click="!isView && showDateTimePicker('reportTime')"
                  >{{ form.reportTime || "请选择" }}</view
                >
                <u-icon slot="right" name="arrow-right" />
              </u-form-item>
            </u--form>
          </view>

          <!-- 调查处理信息 -->
          <view class="card-section" v-if="!isView || form.acdntLevelId">
            <view class="section-title">🔍 调查处理信息</view>
            <u--form
              labelPosition="left"
              labelWidth="180rpx"
              :model="form"
              ref="form2Ref"
            >
              <u-form-item
                label="事故级别"
                prop="acdntLevelId"
                borderBottom
                required
              >
                <DictSelection
                  dictName="事故级别"
                  clearable
                  :disabled="isView"
                  v-model="formData.acdntLevelId"
                />
              </u-form-item>
              <u-form-item
                label="事故事件类型"
                prop="acdntTypeId"
                borderBottom
                required
              >
                <DictSelection
                  dictName="事故事件类型"
                  clearable
                  :disabled="isView"
                  v-model="formData.acdntTypeId"
                />
              </u-form-item>
              <u-form-item label="事故原因" prop="acdntCauselText" borderBottom>
                <u--textarea
                  v-model="form.acdntCauselText"
                  placeholder="请输入"
                  :disabled="isView"
                  border="none"
                  height="120rpx"
                />
              </u-form-item>
              <u-form-item
                label="事故责任人"
                prop="dutyPersonName"
                borderBottom
              >
                <u--input
                  v-model="form.dutyPersonName"
                  placeholder="请选择"
                  readonly
                  :disabled="isView"
                  border="none"
                  inputAlign="right"
                  @click="userOpen('duty')"
                />
              </u-form-item>
              <u-form-item label="责任单位" borderBottom>
                <u--input
                  v-model="form.dutyUnitName"
                  disabled
                  border="none"
                  inputAlign="right"
                />
              </u-form-item>
              <u-form-item label="间接经济损失(万元)" borderBottom>
                <u--input
                  v-model="form.indirectEconomicLoss"
                  type="number"
                  placeholder="请输入"
                  :disabled="isView"
                  border="none"
                  inputAlign="right"
                />
              </u-form-item>
              <u-form-item label="直接经济损失(万元)" borderBottom>
                <u--input
                  v-model="form.directEconomicLoss"
                  type="number"
                  placeholder="请输入"
                  :disabled="isView"
                  border="none"
                  inputAlign="right"
                />
              </u-form-item>
            </u--form>
          </view>

          <!-- 伤亡人员列表 -->
          <view class="card-section">
            <view class="section-title"
              >👥 伤亡人员列表
              <text class="add-btn" v-if="!isView" @click="userOpen('casualty')"
                >+ 添加</text
              ></view
            >
            <view
              v-for="(p, idx) in form.ehsAccidentCasualtiesVOList"
              :key="idx"
              class="person-item"
            >
              <view class="person-info"
                ><text class="name">{{ p.userName }}</text
                ><text class="dept">{{ p.userDeptName }}</text></view
              >
              <view class="person-extra">
                <picker
                  mode="selector"
                  :range="injuryDegreeOptions"
                  range-key="label"
                  :value="injuryDegreeIndex(p.injuryDegree)"
                  @change="(e) => onInjuryChange(e, idx)"
                  :disabled="isView"
                >
                  <view class="tag">{{
                    getInjuryLabel(p.injuryDegree) || "受伤程度"
                  }}</view>
                </picker>
                <input
                  class="days-input"
                  v-model="p.lostWorkDays"
                  type="number"
                  placeholder="损失工作日"
                  :disabled="isView"
                />
                <text class="delete" v-if="!isView" @click="removeCasualty(idx)"
                  >✕</text
                >
              </view>
            </view>
            <view
              v-if="form.ehsAccidentCasualtiesVOList.length === 0"
              class="empty-tip"
              >暂无伤亡人员</view
            >
          </view>
        </view>
      </scroll-view>

      <view class="popup-footer">
        <u-button type="default" @click="cancel">取消</u-button>
        <u-button v-if="!isView" type="primary" @click="save" :loading="loading"
          >保存</u-button
        >
      </view>
    </view>

    <!-- 选择器：字典、日期、人员等 -->
    <u-action-sheet
      :show="showDictPopup"
      :actions="dictActions"
      @close="showDictPopup = false"
      @select="onDictSelect"
    />
    <u-datetime-picker
      :show="showDateTimePopup"
      v-model="datetimeValue"
      mode="datetime"
      @confirm="onDateTimeConfirm"
      @cancel="showDateTimePopup = false"
    />
    <selectUserDialog ref="userSelectRef" @confirm="changePersonel" />
    <drillOrderSelect
      ref="drillOrderSelectRef"
      @confirm="onDrillOrderConfirm"
    />
    <u-toast ref="uToast" />
  </u-popup>
</template>

<script>
import drillOrderSelect from "./drillOrderSelect.vue";
import selectUserDialog from "@/components/selectUserDialog.vue";
import { save, getById } from "@/api/accidentReport/index.js";
import dictMixins from "@/mixins/dictMixins";

const defForm = {
  acdntName: "",
  occurrenceTime: "",
  acdntPlace: "",
  acdntPass: "",
  sourceType: "",
  sourceName: "",
  sourceId: "",
  reportPersonName: "",
  reportPersonUserId: "",
  reportDeptName: "",
  reportDeptId: "",
  reportTime: "",
  acdntLevelId: "",
  acdntTypeId: "",
  acdntCauselText: "",
  dutyUnitId: "",
  dutyUnitName: "",
  dutyPersonName: "",
  dutyPersonId: "",
  indirectEconomicLoss: undefined,
  directEconomicLoss: undefined,
  ehsAccidentCasualtiesVOList: [],
};

export default {
  components: { selectUserDialog, drillOrderSelect },
  mixins: [dictMixins],
  data() {
    return {
      visible: false,
      loading: false,
      dialogType: "add",
      form: JSON.parse(JSON.stringify(defForm)),
      injuryDegreeOptions: [
        { value: "1", label: "轻微伤" },
        { value: "2", label: "轻伤二级" },
        { value: "3", label: "轻微一级" },
        { value: "4", label: "重伤二级" },
        { value: "5", label: "重伤一级" },
      ],
      showDictPopup: false,
      dictActions: [],
      dictField: "",
      showDateTimePopup: false,
      datetimeValue: 0,
      dateField: "",
      selectMode: "",
      rules: {
        acdntName: { required: true, message: "请输入事故事件名称" },
        occurrenceTime: { required: true, message: "请选择发生时间" },
        acdntPlace: { required: true, message: "请输入事故发生地点" },
        acdntPass: { required: true, message: "请输入事故事件经过" },
        reportTime: { required: true, message: "请选择上报时间" },
        acdntLevelId: { required: true, message: "请选择事故级别" },
        acdntTypeId: { required: true, message: "请选择事故事件类型" },
      },
    };
  },
  computed: {
    dialogTitle() {
      return (
        { add: "新增事故上报", edit: "编辑事故上报", view: "查看事故上报" }[
          this.dialogType
        ] || "事故上报"
      );
    },
    isView() {
      return this.dialogType === "view";
    },
  },
  methods: {
    async open(row, type = "add") {
      this.visible = true;
      this.dialogType = type;
      if (row && row.id) {
        const data = await getById(row.id);
        this.form = { ...JSON.parse(JSON.stringify(defForm)), ...data };
        if (!this.form.ehsAccidentCasualtiesVOList)
          this.form.ehsAccidentCasualtiesVOList = [];
      } else {
        this.form = JSON.parse(JSON.stringify(defForm));
        const userInfo = uni.getStorageSync("userInfo") || {};
        this.form.reportPersonName = userInfo.name || "";
        this.form.reportPersonUserId = userInfo.userId || "";
        this.form.reportDeptName = userInfo.groupName || "";
        this.form.reportDeptId = userInfo.groupId || "";
      }
      this.$nextTick(() => {
        if (this.$refs.formRef) this.$refs.formRef.setRules(this.rules);
      });
    },
    cancel() {
      this.visible = false;
      this.form = JSON.parse(JSON.stringify(defForm));
    },

    // 日期选择
    showDateTimePicker(field) {
      if (this.isView) return;
      this.dateField = field;
      this.datetimeValue = this.form[field]
        ? new Date(this.form[field]).getTime()
        : Date.now();
      this.showDateTimePopup = true;
    },
    onDateTimeConfirm(e) {
      this.showDateTimePopup = false;
      this.form[this.dateField] = this.$u.timeFormat(
        e.value,
        "yyyy-mm-dd hh:MM:ss",
      );
    },

    onDictSelect(e) {
      this.showDictPopup = false;
      this.form[this.dictField] = e.value;
      if (this.$refs.formRef) this.$refs.formRef.validateField(this.dictField);
    },

    // 来源类型
    getSourceTypeLabel(val) {
      const map = { 1: "应急演练工单" };
      return map[val] || "";
    },
    showSourceTypePicker() {
      if (this.isView) return;
      this.dictField = "sourceType";
      this.dictActions = [{ name: "应急演练工单", value: "1" }];
      this.showDictPopup = true;
    },

    // 来源单据
    addSource() {
      if (this.isView) return;
      if (!this.form.sourceType) {
        this.$refs.uToast.show({
          type: "warning",
          message: "请先选择来源类型",
        });
        return;
      }
      if (this.form.sourceType == "1") this.$refs.drillOrderSelectRef.open();
    },
    onDrillOrderConfirm(data) {
      this.form.sourceName = data.name || "";
      this.form.sourceId = data.id || "";
      this.form.acdntPlace = data.planLocation || "";
    },

    // 打开人员选择
    userOpen(key) {
      if (this.isView || this.loading) return;
      this.userKey = key;
      // 上报人、责任人：单选
      if (key === "report" || key === "duty") {
        this.$refs.userSelectRef.open(2);
      }
      // 伤亡人员：多选，传入已选列表禁用
      if (key === "casualty") {
        const disabledList = this.form.ehsAccidentCasualtiesVOList.map(
          (item) => ({
            id: item.userId,
          }),
        );
        this.$refs.userSelectRef.open(1);
      }
    },

    // 统一回调
    changePersonel(data) {
      if (!data || data.length === 0) return;

      if (this.userKey === "report") {
        const person = data[0];
        this.form.reportPersonName = person.name || "";
        this.form.reportPersonUserId = person.id || "";
        this.form.reportDeptName = person.groupName || "";
        this.form.reportDeptId = person.groupId || "";
      } else if (this.userKey === "duty") {
        const person = data[0];
        this.form.dutyPersonName = person.name || "";
        this.form.dutyPersonId = person.id || "";
        this.form.dutyUnitName = person.groupName || "";
        this.form.dutyUnitId = person.groupId || "";
      } else if (this.userKey === "casualty") {
        data.forEach((person) => {
          this.form.ehsAccidentCasualtiesVOList.push({
            userId: person.id || "",
            userName: person.name || "",
            userDeptId: person.groupId || "",
            userDeptName: person.groupName || "",
            injuryDegree: "",
            lostWorkDays: undefined,
            accidentId: this.form.id || "",
          });
        });
      }
    },

    // 伤亡人员受伤程度
    injuryDegreeIndex(val) {
      return this.injuryDegreeOptions.findIndex((i) => i.value == val);
    },
    getInjuryLabel(val) {
      const item = this.injuryDegreeOptions.find((i) => i.value == val);
      return item ? item.label : "";
    },
    onInjuryChange(e, idx) {
      const val = this.injuryDegreeOptions[e.detail.value]?.value;
      this.$set(
        this.form.ehsAccidentCasualtiesVOList[idx],
        "injuryDegree",
        val,
      );
    },
    removeCasualty(idx) {
      this.form.ehsAccidentCasualtiesVOList.splice(idx, 1);
    },

    // 保存
    async save() {
      try {
        await this.$refs.formRef.validate();
        // 填充分类名称
        this.form.acdntLevelName = this.getDictValue(
          "事故级别",
          this.form.acdntLevelId,
        );
        this.form.acdntTypeName = this.getDictValue(
          "事故事件类型",
          this.form.acdntTypeId,
        );
        this.loading = true;
        await save(this.form);
        this.$refs.uToast.show({ type: "success", message: "保存成功" });
        this.cancel();
        this.$emit("reload");
      } catch (e) {
        if (e && e.message)
          this.$refs.uToast.show({ type: "error", message: e.message });
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.accident-popup {
  /deep/ .u-popup__content {
    border-radius: 32rpx 32rpx 0 0;
    overflow: hidden;
  }
}
.popup-content {
  height: 80vh;
  display: flex;
  flex-direction: column;
  background: #eff2f7;
}
.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx 32rpx;
  background: #fff;
  border-bottom: 2rpx solid #eef2f6;
  flex-shrink: 0;
  .popup-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #1f2b3c;
  }
  .close-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 52rpx;
    color: #8e9aae;
  }
}
.popup-body {
  flex: 1;
  overflow-y: auto;
  padding: 24rpx;
}
.card-a {
  background: #fff;
  border-radius: 48rpx;
  box-shadow: 0 12rpx 40rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}
.card-section {
  padding: 30rpx 32rpx;
  &:not(:last-child) {
    border-bottom: 2rpx solid #f0f2f5;
  }
}
.section-title {
  font-size: 30rpx;
  font-weight: 700;
  color: #1f2a44;
  margin-bottom: 24rpx;
  padding-left: 16rpx;
  border-left: 6rpx solid #4caf50;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .add-btn {
    font-size: 26rpx;
    color: #2979ff;
    font-weight: normal;
    padding: 4rpx 16rpx;
    background: #e8f0fe;
    border-radius: 30rpx;
  }
}
/deep/ .u-form-item {
  padding: 12rpx 0;
  .u-form-item__body__left__label {
    font-size: 26rpx !important;
    color: #6c7a91 !important;
  }
  .u-input__content__field-wrapper__field {
    font-size: 26rpx !important;
    text-align: right;
  }
}
.picker-value {
  font-size: 26rpx;
  color: #1e2a3a;
  text-align: right;
  flex: 1;
  min-height: 44rpx;
  padding: 4rpx 0;
}
.person-item {
  background: #f5f7fb;
  border-radius: 16rpx;
  padding: 16rpx;
  margin-bottom: 12rpx;
  .person-info {
    display: flex;
    gap: 20rpx;
    .name {
      font-weight: 600;
      font-size: 28rpx;
    }
    .dept {
      color: #8e9aae;
      font-size: 24rpx;
    }
  }
  .person-extra {
    display: flex;
    align-items: center;
    gap: 12rpx;
    margin-top: 8rpx;
    .tag {
      background: #e8edf4;
      padding: 4rpx 16rpx;
      border-radius: 30rpx;
      font-size: 24rpx;
      color: #2979ff;
    }
    .days-input {
      flex: 1;
      background: #fff;
      border-radius: 30rpx;
      padding: 0 16rpx;
      height: 50rpx;
      font-size: 24rpx;
    }
    .delete {
      color: #f56c6c;
      font-size: 28rpx;
      padding: 0 8rpx;
    }
  }
}
.empty-tip {
  text-align: center;
  font-size: 26rpx;
  color: #aaa;
  padding: 30rpx 0;
}
.popup-footer {
  display: flex;
  padding: 16rpx 24rpx;
  background: #fff;
  border-top: 2rpx solid #eef2f6;
  gap: 16rpx;
  flex-shrink: 0;
  /deep/ .u-button {
    flex: 1;
    border-radius: 48rpx;
    height: 72rpx;
  }
}
</style>
