<template>
  <view class="container">
    <uni-nav-bar
      fixed="true"
      statusBar="true"
      left-icon="back"
      title="转生产订单"
      background-color="#157A2C"
      color="#fff"
      @clickLeft="back"
    ></uni-nav-bar>

    <scroll-view scroll-y class="content">
      <view class="form-section">
        <view class="section-title">基本信息</view>

        <view class="form-item">
          <text class="label">所属工厂</text>
          <input class="input" v-model="form.applyFactoriesName" disabled />
        </view>

        <view class="form-item">
          <text class="label">请托部门</text>
          <input class="input" v-model="form.applyDeptName" disabled />
        </view>

        <view class="form-item">
          <text class="label">请托人</text>
          <input class="input" v-model="form.createUserName" disabled />
        </view>

        <view class="form-item">
          <text class="label">受托工厂</text>
          <input
            class="input"
            v-model="form.beEntrustedFactoriesName"
            disabled
          />
        </view>

        <view class="form-item">
          <text class="label">受托部门</text>
          <input class="input" v-model="form.beEntrustedDeptName" disabled />
        </view>

        <view class="form-item">
          <text class="label">类型</text>
          <input class="input" :value="getTypeText(form.type)" disabled />
        </view>
      </view>

      <view class="form-section">
        <view class="section-title">产品信息</view>

        <view class="form-item">
          <text class="label">名称</text>
          <input class="input" v-model="form.productName" disabled />
        </view>

        <view class="form-item">
          <text class="label">编码</text>
          <input class="input" v-model="form.productCode" disabled />
        </view>

        <view class="form-item">
          <text class="label">牌号</text>
          <input class="input" v-model="form.brandNo" disabled />
        </view>

        <view class="form-item">
          <text class="label">型号</text>
          <input class="input" v-model="form.model" disabled />
        </view>

        <view class="form-item">
          <text class="label">规格</text>
          <input class="input" v-model="form.specification" disabled />
        </view>

        <view class="form-item">
          <text class="label">批次号</text>
          <input class="input" v-model="form.batchNo" disabled />
        </view>

        <view class="form-item">
          <text class="label">订单数量</text>
          <view class="input-group">
            <input class="input" v-model="form.contractNum" disabled />
            <text class="unit">{{ form.measuringUnit }}</text>
          </view>
        </view>

        <view class="form-item">
          <text class="label">完成日期</text>
          <input class="input" v-model="form.planDeliveryTime" disabled />
        </view>

        <view class="form-item">
          <text class="label">计划开始时间</text>
          <input class="input" v-model="form.planStartTime" disabled />
        </view>

        <view class="form-item">
          <text class="label">计划结束时间</text>
          <input class="input" v-model="form.planCompleteTime" disabled />
        </view>

        <view class="form-item required">
          <text class="label">工艺路线</text>
          <view class="input clickable" @click="chooseRoute">
            <text
              :class="
                form.produceRoutingName ? 'input-text' : 'placeholder-text'
              "
            >
              {{ form.produceRoutingName || "请选择工艺路线" }}
            </text>
          </view>
        </view>

        <view class="form-item">
          <text class="label">紧急程度</text>
          <input
            class="input"
            :value="getPriorityText(form.priority)"
            disabled
          />
        </view>

        <view class="form-item">
          <text class="label">需求描述</text>
          <textarea class="textarea" v-model="form.describes" disabled />
        </view>
      </view>
    </scroll-view>

    <view class="footer">
      <button class="btn-cancel" @click="cancel">取消</button>
      <button class="btn-confirm" @click="save">确定</button>
    </view>

    <view
      class="popup-mask"
      v-if="showRoutePicker"
      @click="showRoutePicker = false"
    >
      <view class="popup-content" @click.stop>
        <view class="popup-header">
          <text class="popup-title">选择工艺路线</text>
          <text class="popup-close" @click="showRoutePicker = false">✕</text>
        </view>
        <scroll-view scroll-y class="popup-list">
          <view
            class="popup-item"
            v-for="item in routeList"
            :key="item.id"
            :class="{ active: form.produceRoutingId === item.id }"
            @click="selectRoute(item)"
          >
            <text>{{ item.name }}</text>
            <text v-if="form.produceRoutingId === item.id" class="check-icon"
              >✓</text
            >
          </view>
          <view v-if="routeList.length === 0" class="popup-empty"
            >暂无工艺路线</view
          >
        </scroll-view>
      </view>
    </view>
  </view>
</template>

<script>
import { beEntrustDetail, createProductionOrder } from "@/api/beEntrust/index";
import { producerouting } from "@/api/pda/workOrder";

export default {
  data() {
    return {
      id: "",
      showRoutePicker: false,
      routeList: [],
      form: {
        applyFactoriesName: "",
        applyDeptName: "",
        createUserName: "",
        beEntrustedFactoriesName: "",
        beEntrustedDeptName: "",
        type: "",
        productName: "",
        productCode: "",
        brandNo: "",
        model: "",
        specification: "",
        batchNo: "",
        contractNum: "",
        measuringUnit: "",
        planDeliveryTime: "",
        planStartTime: "",
        planCompleteTime: "",
        produceRoutingName: "",
        produceRoutingId: "",
        priority: "",
        describes: "",
        sourceId: "",
        sourceCode: "",
      },
    };
  },

  onLoad(options) {
    this.id = options.id;
    if (this.id) {
      this.loadData();
    }
  },

  methods: {
    back() {
      uni.navigateBack();
    },

    async loadData() {
      try {
        const res = await beEntrustDetail(this.id);
        const data = JSON.parse(JSON.stringify(res));
        data.productCode = data.categoryCode;
        data.productName = data.categoryName;
        data.model = data.modelType;
        data.brandNo = data.brandNum;
        data.contractNum = data.totalCount;
        data.sourceCode = data.code;
        data.sourceId = data.id;
        data.formingWeight = data.totalWeight;
        data.newWeightUnit = data.weightUnit;
        data.produceRoutingId = "";
        data.produceRoutingName = "";

        this.form = data;
      } catch (error) {
        uni.showToast({
          title: "加载失败",
          icon: "none",
        });
      }
    },

    getTypeText(type) {
      const map = { 1: "加工", 2: "装配" };
      return map[type] || "";
    },

    getPriorityText(priority) {
      const map = { 1: "一般", 2: "紧急" };
      return map[priority] || "";
    },

    async chooseRoute() {
      try {
        const res = await producerouting({
          pageNum: 1,
          size: -1,
          routeType: 2,
        });
        this.routeList = (res.list || res || []).map((item) => ({
          id: item.id,
          name: item.name,
        }));
        this.showRoutePicker = true;
      } catch (error) {
        uni.showToast({
          title: "获取工艺路线失败",
          icon: "none",
        });
      }
    },

    selectRoute(item) {
      this.form.produceRoutingId = item.id;
      this.form.produceRoutingName = item.name;
      this.showRoutePicker = false;
    },

    cancel() {
      uni.navigateBack();
    },

    save() {
      if (!this.form.produceRoutingName) {
        uni.showToast({
          title: "请选择工艺路线",
          icon: "none",
        });
        return;
      }

      uni.showModal({
        title: "提示",
        content: "确定转为生产订单吗？",
        success: (res) => {
          if (res.confirm) {
            this.doSave();
          }
        },
      });
    },

    async doSave() {
      uni.showLoading({ title: "提交中..." });
      try {
        let params = {
          ...this.form,
          sourceType: 3,
        };

        if (params.planDeliveryTime) {
          params.planDeliveryTime = params.planDeliveryTime.split(" ")[0];
        }

        await createProductionOrder(params);

        uni.hideLoading();
        uni.showToast({
          title: "转换成功",
          icon: "success",
        });
        setTimeout(() => {
          uni.navigateBack();
        }, 1500);
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: "转换失败",
          icon: "none",
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f5f5f5;
}

.content {
  flex: 1;
  padding: 20rpx;
}

.form-section {
  background-color: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;

  .section-title {
    font-size: 32rpx;
    font-weight: bold;
    color: #333;
    margin-bottom: 24rpx;
    padding-bottom: 16rpx;
    border-bottom: 2rpx solid #f0f0f0;
  }
}

.form-item {
  display: flex;
  align-items: center;
  margin-bottom: 24rpx;

  &.required .label::before {
    content: "*";
    color: #f56c6c;
    margin-right: 4rpx;
  }

  .label {
    width: 200rpx;
    flex-shrink: 0;
    font-size: 28rpx;
    color: #666;
  }

  .input {
    flex: 1;
    height: 64rpx;
    line-height: 64rpx;
    padding: 0 16rpx;
    background-color: #f5f5f5;
    border: none;
    border-radius: 8rpx;
    font-size: 28rpx;
    color: #333;
    box-sizing: border-box;
  }

  /deep/ .uni-input-wrapper,
  /deep/ .uni-input-input {
    height: 64rpx !important;
    line-height: 64rpx !important;
    min-height: auto !important;
    border: none !important;
    outline: none !important;
    background: transparent !important;
    font-size: 28rpx !important;
    color: #333 !important;
  }

  .input-group {
    flex: 1;
    display: flex;
    align-items: center;
    gap: 8rpx;

    .input {
      flex: 1;
    }

    .unit {
      font-size: 28rpx;
      color: #999;
      flex-shrink: 0;
    }
  }

  .textarea {
    flex: 1;
    padding: 16rpx;
    background-color: #f5f5f5;
    border: none;
    border-radius: 8rpx;
    font-size: 28rpx;
    color: #333;
    min-height: 120rpx;
    box-sizing: border-box;
  }
}

.footer {
  display: flex;
  gap: 20rpx;
  padding: 20rpx;
  background-color: #fff;
  box-shadow: 0 -2rpx 8rpx rgba(0, 0, 0, 0.08);

  button {
    flex: 1;
    height: 80rpx;
    line-height: 80rpx;
    font-size: 30rpx;
    border-radius: 12rpx;
  }

  .btn-cancel {
    background-color: #fff;
    color: #666;
    border: 1rpx solid #e0e0e0;
  }

  .btn-confirm {
    background-color: #157a2c;
    color: #fff;
  }
}

.clickable {
  display: flex;
  align-items: center;
  justify-content: space-between;

  .input-text {
    font-size: 28rpx;
    color: #333;
  }

  .placeholder-text {
    font-size: 28rpx;
    color: #999;
  }

  .arrow {
    font-family: uniicons;
    font-size: 28rpx;
    color: #999;
  }
}

.popup-mask {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  z-index: 999;
  display: flex;
  align-items: flex-end;
}

.popup-content {
  width: 100%;
  background-color: #fff;
  border-radius: 24rpx 24rpx 0 0;
  max-height: 70vh;
  display: flex;
  flex-direction: column;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 28rpx 32rpx;
  border-bottom: 1rpx solid #f0f0f0;

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

  .popup-close {
    font-size: 36rpx;
    color: #999;
    padding: 8rpx;
  }
}

.popup-list {
  max-height: 60vh;
  padding: 0 32rpx;
}

.popup-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 28rpx 16rpx;
  border-bottom: 1rpx solid #f5f5f5;
  font-size: 28rpx;
  color: #333;

  &.active {
    color: #157a2c;
    font-weight: bold;
  }

  .check-icon {
    color: #157a2c;
    font-size: 32rpx;
  }
}

.popup-empty {
  text-align: center;
  padding: 60rpx 0;
  font-size: 28rpx;
  color: #999;
}
</style>
