<template>
  <u-popup
    :show="visible"
    :round="0"
    :closeOnClickOverlay="false"
    :zIndex="99999"
    @close="handleCancel"
    class="u-popup-my"
  >
    <view class="popup-content">
      <view class="popup-header">
        <text class="popup-title">{{ dialogTitle }}</text>
        <view class="close-btn" @click="handleCancel">×</view>
      </view>

      <scroll-view class="popup-body" scroll-y>
        <view class="page">
          <view class="card-a">
            <!-- 头部 -->
            <view class="a-header">
              <text class="a-main-title">随手拍记录</text>
            </view>

            <!-- 基础信息 -->
            <view class="card-section">
              <view class="section-title">📝 基础信息</view>
              <view class="info-list">
                <view class="info-item">
                  <text class="info-label">问题描述</text>
                  <textarea
                    v-if="canEdit"
                    class="info-textarea"
                    v-model="formData.description"
                    placeholder="请输入问题描述"
                    :disabled="!canEdit"
                  />
                  <text v-else class="info-value readonly">{{
                    formData.description
                  }}</text>
                </view>
                <view class="info-item">
                  <text class="info-label">问题所在位置</text>
                  <input
                    v-if="canEdit"
                    class="info-input"
                    v-model="formData.location"
                    placeholder="请输入位置"
                    :disabled="!canEdit"
                  />
                  <text v-else class="info-value readonly">{{
                    formData.location
                  }}</text>
                </view>
                <view class="info-item">
                  <text class="info-label">问题所属部门</text>

                  <view
                    class="info-value"
                    :class="{ disabled: !canEdit }"
                    @click="title != '详情' && $refs.treePicker._show()"
                  >
                    {{ formData.problemDeptName || "请选择" }}
                  </view>
                </view>
                <view class="info-item">
                  <text class="info-label">随手拍图片</text>
                  <fileMain
                    v-model="formData.attachment"
                    :type="canEdit ? '' : 'view'"
                  />
                </view>
              </view>
            </view>

            <!-- 上报信息 -->
            <view class="card-section">
              <view class="section-title">👤 上报信息</view>
              <view class="info-list">
                <view class="info-item">
                  <text class="info-label">上报人</text>
                  <text class="info-value readonly">{{
                    formData.reporterName
                  }}</text>
                </view>
                <view class="info-item">
                  <text class="info-label">上报人部门</text>
                  <text class="info-value readonly">{{
                    formData.reporterDeptName
                  }}</text>
                </view>
                <view class="info-item" v-if="!canEdit">
                  <text class="info-label">处理结果</text>
                  <view >
                    <text
                      v-if="formData.handleResult == 0"
                      class="status-pending"
                      >待处理</text
                    >
                    <text
                      v-else
                      class="status-link"
                      :class="{
                        'status-done': formData.handleResult == 1,
                        'status-discard': formData.handleResult == 2,
                      }"
                      @click="handleViewResult"
                      >{{ getResultLabel(formData.handleResult) }}（点击查看）</text
                    >
                  </view>
                </view>
              </view>
            </view>
          </view>
        </view>
      </scroll-view>

      <view class="popup-footer">
        <template v-if="isView">
          <u-button type="default" @click="handleCancel">关闭</u-button>
        </template>
        <template v-else-if="isHandle">
          <u-button type="default" @click="handleDiscard">废弃</u-button>
          <u-button type="primary" @click="handleRectify">下发整改</u-button>
        </template>
        <template v-else>
          <u-button type="default" @click="handleCancel">取消</u-button>
          <u-button type="primary" @click="handleSubmit" :loading="loading"
            >保存</u-button
          >
        </template>
      </view>
    </view>
    <u-toast ref="uToast"></u-toast>
    <ba-tree-picker
      ref="treePicker"
      key="verify"
      :multiple="false"
      @select-change="searchDeptNodeClick"
      title="选择部门"
      :localdata="classificationList"
      valueKey="id"
      textKey="name"
      childrenKey="children"
    />
  </u-popup>
</template>

<script>
import { getById, save, update } from "@/api/snapshot/index.js";
import fileMain from "@/pages/doc/index.vue";
import { listOrganizations } from "@/api/common.js";
import { toTreeData } from "@/utils/utils.js";
export default {
  emits: ["reload", "rectify", "discard"],
  components: {
    fileMain,
  },
  data() {
    return {
      visible: false,
      loading: false,
      dialogType: "add",
      formData: this.getDefaultForm(),
      classificationList: [],
      resultOptions: [
        {
          value: 1,
          label: "下发整改",
        },
        {
          value: 2,
          label: "废弃",
        },
      ],
    };
  },
  computed: {
    dialogTitle() {
      const map = {
        add: "新增随手拍",
        edit: "编辑随手拍",
        view: "随手拍详情",
        handle: "随手拍处理",
      };
      return map[this.dialogType] || "随手拍";
    },
    isView() {
      return this.dialogType === "view";
    },
    isHandle() {
      return this.dialogType === "handle";
    },
    canEdit() {
      return ["add", "edit"].includes(this.dialogType);
    },
  },
  methods: {
    getDefaultForm() {
      return {
        id: "",
        description: "",
        location: "",
        problemDeptId: "",
        problemDeptName: "",
        attachment: [],
        reporterId: "",
        reporterName: "",
        reporterDeptId: "",
        reporterDeptName: "",
        handleResult: 0,
        handleOpinion: "",
        invHazardId: "",
      };
    },
    async getTreeList() {
      const data = await listOrganizations({});
      let treeList = toTreeData({
        data: data || [],
        idField: "id",
        parentIdField: "parentId",
      });
      this.classificationList = treeList;
    },
    async open(type, row = null) {
      console.log(row, "type");
      this.dialogType = type;
      if (row && row.id && ["edit", "view", "handle"].includes(type)) {
        try {
          const data = await getById(row.id);
          this.formData = {
            ...data,
            attachment: data.attachment || [],
          };
        } catch (e) {
          console.error(e);
        }
      } else {
        this.formData = this.getDefaultForm();
        const userInfo = uni.getStorageSync("userInfo") || {};
        this.formData.reporterName = userInfo.name || "";
        this.formData.reporterId = userInfo.userId || "";
        this.formData.reporterDeptName = userInfo.groupName || "";
        this.formData.reporterDeptId = userInfo.groupId || "";
      }
      this.getTreeList();
      this.visible = true;
    },
    //选择部门(搜索)
    async searchDeptNodeClick(id, name, type) {
      this.formData.problemDeptId = id[0];
      this.formData.problemDeptName = name;
    },
    handleCancel() {
      this.visible = false;
      this.resetForm();
    },
    resetForm() {
      this.formData = this.getDefaultForm();
    },
    getResultLabel(result) {
      const item = this.resultOptions.find((opt) => opt.value == result);
      return item ? item.label : "待处理";
    },
    previewImage(url) {
      uni.previewImage({
        urls: [url],
      });
    },
    handleViewResult() {
      if (this.formData.handleResult == 2) {
        this.$emit("discard", this.formData, "view");
      } else if (this.formData.handleResult == 1 && this.formData.invHazardId) {
        uni.navigateTo({
          url: `/pages/hazard/detail?id=${this.formData.invHazardId}`,
        });
      }
    },
    async handleSubmit() {
      // 简单校验
      if (!this.formData.description) {
        this.$refs.uToast.show({
          type: "error",
          message: "请输入问题描述",
        });
        return;
      }
      if (!this.formData.location) {
        this.$refs.uToast.show({
          type: "error",
          message: "请输入问题所在位置",
        });
        return;
      }
      const api = this.dialogType === "add" ? save : update;
      this.loading = true;
      try {
        await api(this.formData);
        this.$refs.uToast.show({
          type: "success",
          message: this.dialogType === "add" ? "新增成功" : "编辑成功",
        });
        this.visible = false;
        this.$emit("reload");
        this.resetForm();
      } catch (e) {
        console.error(e);
      } finally {
        this.loading = false;
      }
    },
    handleRectify() {
      this.$emit("rectify", this.formData);
      this.visible = false;
    },
    handleDiscard() {
      this.$emit("discard", this.formData);
      this.visible = false;
    },
  },
};
</script>

<style lang="scss" scoped>
.popup-content {
  width: 100vw;
  height: calc(100vh - 100px);
  background: #fff;
  border-radius: 0;
  display: flex;
  flex-direction: column;
  background-color: #eff2f7;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #e5e5e5;
  background: #fff;

  .popup-title {
    font-size: 36rpx;
    font-weight: bold;
    color: #333;
  }

  .close-btn {
    width: 60rpx;
    height: 60rpx;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 60rpx;
    color: #999;
    line-height: 1;
  }
}

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

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

.card-a {
  background: #ffffff;
  border-radius: 48rpx;
  box-shadow: 0 12rpx 40rpx rgba(0, 0, 0, 0.05);
  overflow: hidden;
}

.a-header {
  background: linear-gradient(135deg, #e8f5e9 0%, #f1f8e9 100%);
  padding: 40rpx 32rpx 24rpx;
  text-align: center;

  .a-main-title {
    font-size: 36rpx;
    font-weight: 800;
    color: #2e7d32;
  }
}

.card-section {
  padding: 30rpx 32rpx;
  border-bottom: 2rpx solid #f0f2f5;

  &:last-child {
    border-bottom: none;
  }
}

.section-title {
  font-size: 30rpx;
  font-weight: 700;
  color: #1f2a44;
  margin-bottom: 24rpx;
  padding-left: 16rpx;
  border-left: 6rpx solid #4caf50;
}

.info-list {
  display: flex;
  flex-direction: column;
  gap: 28rpx;
}

.info-item {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.info-label {
  font-size: 26rpx;
  font-weight: 600;
  color: #6c7a91;
}

.info-value {
  font-size: 28rpx;
  font-weight: 500;
  color: #1e2a3a;
  padding: 16rpx 20rpx;
  border-radius: 24rpx;
  border: 2rpx solid #e9edf2;
  background: #fff;

  &.readonly {
    color: #999;
    background: #f5f5f5;
  }
}

.info-input,
.info-textarea {
  font-size: 28rpx;
  color: #1e2a3a;
  height: 60rpx;
  padding: 16rpx 20rpx;
  border-radius: 24rpx;
  border: 2rpx solid #e9edf2;
  background: #fff;
}

.info-textarea {
  min-height: 160rpx;
}

.image-list {
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;

  image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 16rpx;
    background: #f5f5f5;
    object-fit: cover;
  }
}

.status-pending {
  color: #e6a23c;
  background: #fff3e0;
  padding: 8rpx 20rpx;
  border-radius: 32rpx;
  font-size: 26rpx;
  display: inline-block;
}

.status-done {
  color: #67c23a;
  background: #e0f3e8;
  padding: 8rpx 20rpx;
  border-radius: 32rpx;
  font-size: 26rpx;
  display: inline-block;
}

.status-discard {
  color: #f56c6c;
  background: #fef0f0;
  padding: 8rpx 20rpx;
  border-radius: 32rpx;
  font-size: 26rpx;
  display: inline-block;
}

.status-link {
  text-decoration: none;
}

.popup-footer {
  display: flex;
  padding: 20rpx 30rpx;
  border-top: 1rpx solid #e5e5e5;
  background: #fff;
  gap: 20rpx;

  /deep/ .u-button {
    flex: 1;
  }
}
</style>
