<template>
  <u-popup
    :show="visible"
    mode="bottom"
    :round="10"
    :closeOnClickOverlay="false"
    @close="close"
    class="transfer-popup"
  >
    <view class="popup-content">
      <!-- 头部 -->
      <view class="popup-header">
        <text class="popup-title">转派</text>
        <view class="close-btn" @click="close">×</view>
      </view>

      <!-- 表单 -->
      <scroll-view class="popup-body" scroll-y>
        <view class="card-a">
          <view class="card-section">
            <u--form
              labelPosition="left"
              labelWidth="160rpx"
              :model="form"
              :rules="rules"
              ref="formRef"
            >
              <!-- 执行部门 -->
              <u-form-item label="执行部门" prop="groupId" borderBottom required>
                <view class="picker-value" @click="showDeptPicker">
                  {{ form.groupName || '请选择部门' }}
                </view>
                <u-icon slot="right" name="arrow-right" />
              </u-form-item>

              <!-- 执行人员 -->
              <u-form-item label="执行人员" prop="qualityId" borderBottom required>
                <view class="picker-value" @click="showUserPicker">
                  {{ form.qualityName || '请选择人员' }}
                </view>
                <u-icon slot="right" name="arrow-right" />
              </u-form-item>
            </u--form>
          </view>
        </view>
      </scroll-view>

      <!-- 底部按钮 -->
      <view class="popup-footer">
        <u-button type="default" @click="close">取消</u-button>
        <u-button type="primary" @click="confirm" :loading="loading">确定</u-button>
      </view>
    </view>

    <!-- 部门树选择器 -->
    <ba-tree-picker
      ref="treePicker"
      key="dept"
      :multiple="false"
      @select-change="onDeptConfirm"
      title="选择部门"
      :localdata="deptList"
      valueKey="id"
      textKey="name"
    />

    <!-- 人员列表选择器（u-picker 单列） -->
    <u-picker
      :show="showUserPickerFlag"
      :columns="[userOptions]"
      keyName="label"
      @confirm="onUserConfirm"
      @cancel="showUserPickerFlag = false"
    />

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

<script>
import baTreePicker from '@/components/ba-tree-picker/ba-tree-picker.vue';
import { transferQualityWork } from '@/api/inspectionWork';
import { listOrganizations,getUserPage } from '@/api/common';

export default {
  components: {
    baTreePicker,
  },
  data() {
    return {
      visible: false,
      loading: false,
      // 表单数据
      form: {
        id: '',          // 质检工单ID
        groupId: '',
        groupName: '',
        qualityId: '',
        qualityName: '',
      },
      // 部门列表（树形）
      deptList: [],
      // 当前部门下的人员列表
      userList: [],
      // 人员选择器显示
      showUserPickerFlag: false,
      // 表单校验规则
      rules: {
        groupId: {
          type: 'string',
          required: true,
          message: '请选择执行部门',
          trigger: ['change'],
        },
        qualityId: {
          type: 'string',
          required: true,
          message: '请选择执行人员',
          trigger: ['change'],
        },
      },
    };
  },
  computed: {
    // 人员选择器选项
    userOptions() {
      return this.userList.map((item) => ({
        label: item.name,
        value: item.id,
      }));
    },
  },
  methods: {
    // ===== 外部调用 =====
    open(id) {
      this.visible = true;
      this.form.id = id || '';
      this.initData();
    },

    // ===== 关闭弹窗 =====
    close() {
      this.visible = false;
      this.resetForm();
      this.showUserPickerFlag = false;
    },

    // ===== 重置表单 =====
    resetForm() {
      this.form = {
        id: '',
        groupId: '',
        groupName: '',
        qualityId: '',
        qualityName: '',
      };
      this.userList = [];
      if (this.$refs.formRef) {
        this.$refs.formRef.clearValidate();
      }
    },

    // ===== 初始化数据 =====
    async initData() {
      try {
        // 1. 加载部门树
        const res = await listOrganizations({});
        this.deptList = res || [];

        // 2. 默认使用当前用户的部门
        const userInfo = uni.getStorageSync('userInfo') || {};
        const defaultGroupId = userInfo.groupId;
        if (defaultGroupId) {
          this.form.groupId = defaultGroupId;
          // 查找部门名称
          const findDept = (list) => {
            for (const item of list) {
              if (item.id === defaultGroupId) return item.name;
              if (item.children) {
                const found = findDept(item.children);
                if (found) return found;
              }
            }
            return null;
          };
          this.form.groupName = findDept(this.deptList) || '';
          // 加载该部门下的人员
          await this.loadUsers(defaultGroupId);
        }
      } catch (e) {
        console.error('初始化失败', e);
      }
    },

    // ===== 加载部门下的人员 =====
    async loadUsers(groupId) {
      if (!groupId) {
        this.userList = [];
        this.form.qualityId = '';
        this.form.qualityName = '';
        return;
      }
      try {
        const res = await getUserPage({
          pageNum: 1,
          size: -1,
          groupId: groupId,
        });
        this.userList = res.list || [];
        // 清空已选人员
        this.form.qualityId = '';
        this.form.qualityName = '';
      } catch (e) {
        console.error('加载人员失败', e);
        this.userList = [];
      }
    },

    // ===== 部门选择 =====
    showDeptPicker() {
      this.$refs.treePicker._show();
    },
    onDeptConfirm(data) {
      const id = data[0];
      if (!id) return;
      this.form.groupId = id;
      // 查找部门名称
      const findDept = (list) => {
        for (const item of list) {
          if (item.id === id) return item.name;
          if (item.children) {
            const found = findDept(item.children);
            if (found) return found;
          }
        }
        return null;
      };
      this.form.groupName = findDept(this.deptList) || '';
      // 加载人员
      this.loadUsers(id);
      // 触发校验
      if (this.$refs.formRef) {
        this.$refs.formRef.validateField('groupId');
      }
    },

    // ===== 人员选择 =====
    showUserPicker() {
      if (!this.form.groupId) {
        this.$refs.uToast.show({
          type: 'warning',
          message: '请先选择执行部门',
        });
        return;
      }
      if (this.userList.length === 0) {
        this.$refs.uToast.show({
          type: 'warning',
          message: '该部门暂无人员',
        });
        return;
      }
      this.showUserPickerFlag = true;
    },
    onUserConfirm(e) {
      const value = e.value[0]?.value;
      const label = e.value[0]?.label;
      if (value) {
        this.form.qualityId = value;
        this.form.qualityName = label;
        if (this.$refs.formRef) {
          this.$refs.formRef.validateField('qualityId');
        }
      }
      this.showUserPickerFlag = false;
    },

    // ===== 提交 =====
    async confirm() {
      try {
        await this.$refs.formRef.validate();
        this.loading = true;
        await transferQualityWork({
          id: this.form.id,
          groupId: this.form.groupId,
          groupName: this.form.groupName,
          qualityId: this.form.qualityId,
          qualityName: this.form.qualityName,
        });
        this.$refs.uToast.show({
          type: 'success',
          message: '转派成功',
        });
        this.$emit('success', this.form.id);
        this.close();
      } catch (e) {
        if (e && e.message) {
          this.$refs.uToast.show({
            type: 'error',
            message: e.message,
          });
        }
      } finally {
        this.loading = false;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.transfer-popup {
  /deep/ .u-popup__content {
    border-radius: 32rpx 32rpx 0 0;
    overflow: hidden;
  }
}

.popup-content {
  height: 50vh;
  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;
}

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

/deep/ .u-form-item {
  padding: 12rpx 0;

  .u-form-item__body__left__label {
    font-size: 26rpx !important;
    color: #6c7a91 !important;
  }

  .u-form-item__body__right__content {
    .u-input__content__field-wrapper__field {
      font-size: 26rpx !important;
      text-align: right;
    }
  }
}

.picker-value {
  font-size: 26rpx;
  color: #1e2a3a;
  padding: 8rpx 0;
  text-align: right;
  flex: 1;
  min-height: 44rpx;
}

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