<template>
  <u-popup
    :show="visible"
    mode="bottom"
    :round="10"
    :closeOnClickOverlay="false"
    @close="cancel"
    class="workorder-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="page">
          <view class="card-a">
            <!-- ===== 基本信息 ===== -->
            <view class="card-section">
              <view class="section-title">📋 基本信息</view>
              <u--form
                labelPosition="left"
                labelWidth="160rpx"
                :model="form"
                :rules="rules"
                ref="formRef"
              >
                <u-form-item label="应急演练计划" prop="planName" borderBottom>
                  <u--input v-model="form.planName" disabled border="none" inputAlign="right" />
                </u-form-item>

                <u-form-item label="应急预案" prop="emergencyPlanName" borderBottom>
                  <view class="link-text" @click="handleViewPlan">
                    {{ form.emergencyPlanName || '请选择' }}
                  </view>
                  <u-icon slot="right" name="arrow-right" />
                </u-form-item>

                <u-form-item label="演练名称" prop="name" borderBottom required>
                  <u--input
                    v-model="form.name"
                    placeholder="请输入"
                    :disabled="isView"
                    border="none"
                    inputAlign="right"
                  />
                </u-form-item>

                <u-form-item label="演练类型" prop="drillType" borderBottom required>
                  <view class="picker-value" @click="!isView && showTypePicker()">
                    {{ getDictValue('应急演练类型', form.drillType) || '请选择' }}
                  </view>
                  <u-icon slot="right" name="arrow-right" />
                </u-form-item>

                <u-form-item label="主管单位" prop="superviseDeptName" borderBottom>
                  <u--input v-model="form.superviseDeptName" disabled border="none" inputAlign="right" />
                </u-form-item>

                <u-form-item label="演练地点" prop="planLocation" borderBottom required>
                  <u--input
                    v-model="form.planLocation"
                    placeholder="请输入"
                    :disabled="isView"
                    border="none"
                    inputAlign="right"
                  />
                </u-form-item>

                <u-form-item label="附件" prop="attachments" borderBottom>
                  <fileMain
                    v-model="form.attachments"
                    :type="isView ? 'view' : ''"
                  />
                </u-form-item>
              </u--form>
            </view>

            <!-- ===== 参演人员 ===== -->
            <view class="card-section">
              <view class="section-title">
                👥 参演人员
                <text class="add-user-btn" v-if="!isView" @click="addUser">+ 添加</text>
              </view>
              <view
                v-for="(person, idx) in form.participantPersonInfo"
                :key="idx"
                class="person-item"
              >
                <view class="person-info">
                  <text class="person-name">{{ person.name }}</text>
                  <text class="person-dept">{{ person.groupName }}</text>
                  <text class="person-phone">{{ person.phone }}</text>
                </view>
                <view class="person-delete" v-if="!isView" @click="removePerson(idx)">
                  <text>✕</text>
                </view>
              </view>
              <view v-if="form.participantPersonInfo.length === 0" class="empty-tip">
                暂无参演人员
              </view>
            </view>

            <!-- ===== 演练记录（仅查看） ===== -->
            <view class="card-section" v-if="isView">
              <view class="section-title">📝 演练记录</view>
              <view class="info-item">
                <text class="info-label">演练实施记录</text>
                <text class="info-value">{{ form.processRecord || '-' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">演练时间</text>
                <text class="info-value">{{ form.drillTime || '-' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">附件</text>
                <fileMain v-model="form.processRecordAttachment" type="view" />
              </view>
            </view>

            <!-- ===== 验收信息（仅查看） ===== -->
            <view class="card-section" v-if="isView">
              <view class="section-title">✅ 验收信息</view>
              <view class="info-item">
                <text class="info-label">演练效果和总结评价</text>
                <text class="info-value">{{ form.drillEvaluation || '-' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">存在的问题及整改措施</text>
                <text class="info-value">{{ form.drillEvaluationMeasure || '-' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">整改情况</text>
                <text class="info-value">{{ form.inspectionRecordRectification || '-' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">验收结果</text>
                <text class="info-value">{{ form.inspectionResult || '-' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">验收人</text>
                <text class="info-value">{{ form.inspectorName || '-' }}</text>
              </view>
              <view class="info-item">
                <text class="info-label">附件</text>
                <fileMain v-model="form.inspectionRecordAttachment" type="view" />
              </view>
            </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="showTypePickerPopup"
      :actions="typeActions"
      title="请选择演练类型"
      @close="showTypePickerPopup = false"
      @select="onTypeSelect"
    />

    <!-- 应急预案查看弹窗 -->
    <emergencyPlanDialog ref="emergencyPlanDialogRef" />



    <u-toast ref="uToast" />
  </u-popup>
</template>

<script>
import emergencyPlanDialog from './emergencyPlanDialog.vue';

import fileMain from '@/pages/doc/index.vue';
import { save, getById, implement } from '@/api/emergencyDrill/workOrder.js';
import dictMixins from '@/mixins/dictMixins';

export default {
  components: {  fileMain,emergencyPlanDialog },
  mixins: [dictMixins],
  data() {
    return {
      visible: false,
      loading: false,
      dialogType: 'add', // add, edit, view
      form: this.getDefaultForm(),
      showTypePickerPopup: false,
      typeActions: [],
      rules: {
        name: { type: 'string', required: true, message: '请输入演练名称', trigger: ['blur', 'change'] },
        drillType: { type: 'string', required: true, message: '请选择演练类型', trigger: ['change'] },
        planLocation: { type: 'string', required: true, message: '请输入演练地点', trigger: ['blur', 'change'] }
      }
    };
  },
  computed: {
    dialogTitle() {
      const map = { add: '新增工单', edit: '编辑工单', view: '工单详情' };
      return map[this.dialogType] || '工单信息';
    },
    isView() {
      return this.dialogType === 'view';
    }
  },
  methods: {
    getDefaultForm() {
      return {
        id: '',
        planId: '',
        planName: '',
        emergencyPlanId: '',
        emergencyPlanName: '',
        name: '',
        drillType: '',
        superviseDeptId: '',
        superviseDeptName: '',
        planLocation: '',
        attachments: [],
        participantPersonInfo: [],
        processRecord: '',
        drillTime: '',
        processRecordAttachment: [],
        drillEvaluation: '',
        drillEvaluationMeasure: '',
        inspectionRecordRectification: '',
        inspectionResult: '',
        inspectorName: '',
        inspectionRecordAttachment: [],
        status: 0
      };
    },

    async open(row, type = 'add') {
      this.visible = true;
      this.dialogType = type;
      this.loading = false;
      this.form = this.getDefaultForm();

      if (row && row.id && type != 'add') {
        try {
          const data = await getById(row.id);
          this.form = { ...data };
        } catch (e) {
          console.error(e);
        }
      } else if (row && row.id) {
        // 从计划创建工单
        this.form.planId = row.id;
        this.form.planName = row.name;
        this.form.emergencyPlanName = row.emergencyPlanName;
        this.form.emergencyPlanId = row.emergencyPlanId;
        this.form.drillType = row.drillType;
        this.form.superviseDeptId = row.responsibleDeptId;
        this.form.superviseDeptName = row.responsibleDeptName;
        this.form.planLocation = row.planLocation;
      }

      // 加载演练类型选项
      this.typeActions = this.getDictOptions('应急演练类型').map(item => ({
        name: item.label,
        value: item.value
      }));

      this.$nextTick(() => {
        if (this.$refs.formRef) {
          this.$refs.formRef.setRules(this.rules);
        }
      });
    },

    cancel() {
      this.visible = false;
      this.form = this.getDefaultForm();
    },

    // 演练类型选择
    showTypePicker() {
      if (this.isView) return;
      this.showTypePickerPopup = true;
    },
    onTypeSelect(e) {
      this.showTypePickerPopup = false;
      this.form.drillType = e.value;
      if (this.$refs.formRef) {
        this.$refs.formRef.validateField('drillType');
      }
    },

    // 查看应急预案
    handleViewPlan() {
      if (this.form.emergencyPlanId) {
        this.$refs.emergencyPlanDialogRef.open({ id: this.form.emergencyPlanId }, 'view');
      }
    },

    // 添加人员
    addUser() {
      this.$refs.userSelectRef.open(null, 0, true);
    },
    changePersonel(list) {
      this.form.participantPersonInfo.push(...list);
    },
    removePerson(index) {
      this.form.participantPersonInfo.splice(index, 1);
    },

    // 保存
    async save() {
      try {
        if (this.$refs.formRef) {
          await this.$refs.formRef.validate();
        }
        if (this.form.participantPersonInfo.length === 0) {
          this.$refs.uToast.show({ type: 'warning', message: '请选择参演人员' });
          return;
        }
        this.loading = true;
        const fn = this.form.id ? save : implement;
        const res = await fn({ workOrder: this.form, id: this.form.planId });
        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>
.workorder-popup {
  /deep/ .u-popup__content {
    border-radius: 32rpx 32rpx 0 0;
    overflow: hidden;
  }

  .popup-content {
    height: calc(100vh - 100px);
    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;
      line-height: 1;
    }
  }

  .popup-body {
    flex: 1;
    overflow-y: auto;
    padding: 24rpx;
  }

  .page {
    font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
  }

  .card-a {
    background: #ffffff;
    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-user-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, .link-text {
    font-size: 26rpx;
    color: #1e2a3a;
    text-align: right;
    flex: 1;
    min-height: 44rpx;
    padding: 4rpx 0;
  }
  .link-text {
    color: #2979ff;
  }

  // 参演人员
  .person-item {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 16rpx 20rpx;
    background: #f5f7fb;
    border-radius: 16rpx;
    margin-bottom: 12rpx;

    .person-info {
      display: flex;
      align-items: center;
      gap: 20rpx;
      flex: 1;
      flex-wrap: wrap;
      .person-name {
        font-size: 28rpx;
        font-weight: 600;
        color: #1f2b3c;
      }
      .person-dept {
        font-size: 24rpx;
        color: #8e9aae;
      }
      .person-phone {
        font-size: 24rpx;
        color: #8e9aae;
      }
    }
    .person-delete {
      width: 48rpx;
      height: 48rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      color: #f56c6c;
      font-size: 28rpx;
    }
  }

  .empty-tip {
    text-align: center;
    font-size: 26rpx;
    color: #aaa;
    padding: 30rpx 0;
  }

  // 信息展示（查看模式）
  .info-item {
    display: flex;
    flex-direction: column;
    gap: 8rpx;
    margin-bottom: 20rpx;
    &:last-child {
      margin-bottom: 0;
    }
    .info-label {
      font-size: 24rpx;
      color: #8e9aae;
    }
    .info-value {
      font-size: 26rpx;
      color: #1f2b3c;
      line-height: 1.6;
    }
  }

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