<template>
  <view class="page-container">
    <!-- 联单生成 -->
    <view class="page-body">
      <view class="form-section">
        <view class="form-group">
          <!-- 处置公司（默认选中第一项） -->
          <view class="form-item">
            <text class="form-label required">处置公司</text>
            <picker :value="selectedTypeIndex" class="form-value" mode="selector" :range="typeCorpOptions" range-key="label" @change="onTypeCorpChange">
              <text>{{ form.type_corp_name || '请选择处置公司' }}</text>
              <uni-icons type="right" size="14" color="#cccccc"></uni-icons>
            </picker>
          </view>
          <!-- 运输经办人（type=3） -->
          <view class="form-item">
            <text class="form-label required">运输经办人</text>
            <picker :value="transportHandlerIndex" class="form-value" mode="selector" :range="transportHandlerOptions" range-key="label" @change="onTransportHandlerChange">
              <text>{{ transportHandlerIndex >= 0 ? transportHandlerOptions[transportHandlerIndex].label : '请选择运输经办人' }}</text>
              <uni-icons type="right" size="14" color="#cccccc"></uni-icons>
            </picker>
          </view>
          <!-- 出库经办人（type=4） -->
          <view class="form-item">
            <text class="form-label required">出库经办人</text>
            <picker :value="outHandlerIndex" class="form-value" mode="selector" :range="outHandlerOptions" range-key="label" @change="onOutHandlerChange">
              <text>{{ outHandlerIndex >= 0 ? outHandlerOptions[outHandlerIndex].label : '请选择出库经办人' }}</text>
              <uni-icons type="right" size="14" color="#cccccc"></uni-icons>
            </picker>
          </view>
        </view>
      </view>

      <!-- 处置公司详情信息 -->
      <view class="data-list" v-if="selectedTypeCorp">
        <view class="data-card">
          <view class="data-card-header"><text class="data-card-title">已选处置公司</text></view>
          <view class="data-card-row"><text>处置公司:</text><text class="val">{{ selectedTypeCorp.jydwmc || '-' }}</text></view>
          <view class="data-card-row"><text>废物名称:</text><text class="val">{{ selectedTypeCorp.fwmc || '-' }}</text></view>
          <view class="data-card-row"><text>废物代码:</text><text class="val">{{ selectedTypeCorp.fwdm || '-' }}</text></view>
        </view>
        <!-- type_corp_info 返回的信息 -->
        <view class="data-card" v-if="typeCorpInfoData.summary_lines && typeCorpInfoData.summary_lines.length">
          <view class="data-card-header" @click="summaryExpanded = !summaryExpanded">
            <text class="data-card-title">汇总信息</text>
            <text class="data-card-toggle">{{ summaryExpanded ? '收起 ▲' : '更多 ▼' }}</text>
          </view>
          <view class="data-card-body" :class="{ collapsed: !summaryExpanded }">
            <view class="data-card-row" v-for="(line, i) in typeCorpInfoData.summary_lines" :key="'s'+i">
              <text class="val summary-text">{{ line }}</text>
            </view>
          </view>
        </view>
        <view class="data-card" v-if="typeCorpInfoData.receiver_company || typeCorpInfoData.transport_company">
          <view class="data-card-header"><text class="data-card-title">企业与经办人</text></view>
          <view class="data-card-row" v-if="typeCorpInfoData.receiver_company"><text>接收企业:</text><text class="val">{{ typeCorpInfoData.receiver_company }}</text></view>
          <view class="data-card-row" v-if="typeCorpInfoData.receiver_handler"><text>出库经办人:</text><text class="val">{{ typeCorpInfoData.receiver_handler }}</text></view>
          <view class="data-card-row" v-if="typeCorpInfoData.transport_company"><text>运输公司:</text><text class="val">{{ typeCorpInfoData.transport_company }}</text></view>
          <view class="data-card-row" v-if="typeCorpInfoData.transport_handler"><text>运输经办人:</text><text class="val">{{ typeCorpInfoData.transport_handler }}</text></view>
        </view>
      </view>

      <!-- 提交按钮 -->
      <view class="btn-area">
        <button class="btn btn-outline" @click="handleQueryManifestList">查询联单列表</button>
        <button class="btn btn-primary btn-block" :disabled="!canSubmit" @click="handleSubmit">联单填领</button>
      </view>

      <!-- 联单列表 -->
      <view class="data-list" v-if="manifestListData.length">
        <view class="data-card" v-for="(item, idx) in manifestListData" :key="idx">
          <view class="data-card-header">
            <text class="data-card-title">联单 {{ idx + 1 }}</text>
            <text class="data-card-tag" :class="item.ldzt === '100' ? 'orange' : 'red'">{{ item.ldzt === '100' ? '待处理' : item.ldzt }}</text>
          </view>
          <view class="data-card-row">
            <text>联单编号:</text>
            <text class="val">{{ item.ldbh || '-' }}</text>
          </view>
          <view class="data-card-row">
            <text>联单类型:</text>
            <text class="val">{{ item.ldlx || '-' }}</text>
          </view>
          <view class="data-card-row">
            <text>运输单位:</text>
            <text class="val">{{ item.ysdwmc || '-' }}</text>
          </view>
          <view class="data-card-row">
            <text>转运数量:</text>
            <text class="val">{{ item.zysl }}</text><text class="val">{{ item.jldw || '' }}</text>
          </view>
          <view class="data-card-row">
            <text>接收数量:</text><text class="val">{{ item.jssl }}</text><text class="val">{{ item.jldw || '' }}</text>
          </view>
          <view class="data-card-row">
            <text>危废运出时间:</text><text class="val">{{ item.wfycsj || '-' }}</text>
          </view>
          <view class="data-card-row">
            <text>办结时间:</text><text class="val">{{ item.bjsj || '-' }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { api } from '@/api/index'
export default {
  data() {
    return {
      /** 处置公司选项 */
      typeCorpOptions: [],
      /** 当前选中项在 typeCorpOptions 中的索引 */
      selectedTypeIndex: -1,
      /** 联单表单 */
      form: {
        type_corp: '',
        type_corp_name: '',
        ysjbr: '',      // 运输经办人编码 type=3
        ckjbr: ''       // 出库经办人编码 type=4
      },
      /** 运输经办人选项（type=3） */
      transportHandlerOptions: [],
      transportHandlerIndex: -1,
      /** 出库经办人选项（type=4） */
      outHandlerOptions: [],
      outHandlerIndex: -1,
      /** 汇总信息是否展开 */
      summaryExpanded: false,
      /** type_corp_info 接口返回数据 */
      typeCorpInfoData: {},
      /** 当前选中的处置公司（typeCorpList 中的原始数据） */
      selectedTypeCorp: null,
      /** 联单列表（manifestList 返回） */
      manifestListData: []
    }
  },
  computed: {
    /** 处置公司已选择且两个经办人都已选择才可提交 */
    canSubmit() {
      return this.form.type_corp !== '' && this.form.ysjbr !== '' && this.form.ckjbr !== ''
    }
  },
  onLoad() {
    // 先加载处置公司列表，再加载详情
    this.initPage()
  },
  methods: {
    // ==================== 页面初始化 ====================
    /** 初始化页面：依次获取 type_corp_list -> type_corp_info */
    async initPage() {
      await this.loadTypeCorpList()
      // 加载经办人列表
      await Promise.all([
        this.loadHandlers(3),
        this.loadHandlers(4)
      ])
      // 默认选中第一项
      if (this.typeCorpOptions.length > 0) {
        const first = this.typeCorpOptions[0]
        this.selectTypeCorp(first)
      }
      // 默认选中经办人第一项
      if (this.transportHandlerOptions.length > 0) {
        this.transportHandlerIndex = 0
        this.form.ysjbr = this.transportHandlerOptions[0].value
      }
      if (this.outHandlerOptions.length > 0) {
        this.outHandlerIndex = 0
        this.form.ckjbr = this.outHandlerOptions[0].value
      }
    },

    // ==================== 数据加载 ====================
    /** 加载处置公司列表（typeCorpList） */
    async loadTypeCorpList() {
      try {
        const res = await api.typeCorpList()
        console.log('[联单] typeCorpList:', res)
        if (res.code === 1000 && res.data) {
          this.typeCorpOptions = (Array.isArray(res.data) ? res.data : (res.data.list || [])).map(item => ({
            value: item.ctid,
            label: item.alias,
            ctid: item.ctid,
            jyqyid: item.jyqyid,
            jydwmc: item.jydwmc,
            cfxxtybh: item.cfxxtybh,
            fwmc: item.fwmc,
            fwdm: item.fwdm
          }))
        }
      } catch (e) {
        console.error('[联单] typeCorpList 加载失败:', e)
      }
    },

    /** 加载处置公司详情（typeCorpInfo）并用返回数据填充表单 */
    async loadTypeCorpInfo(ctid) {
      try {
        const selected = this.typeCorpOptions.find(item => item.ctid === ctid)
        if (!selected) return
        const res = await api.typeCorpInfo({
          ctid: selected.ctid,
          cfxxtybh: selected.cfxxtybh,
          jyqyid: selected.jyqyid
        })
        console.log('[联单] typeCorpInfo:', res)
        if (res.code === 1000 && res.data) {
          this.typeCorpInfoData = res.data
        } else {
          this.typeCorpInfoData = {}
        }
      } catch (e) {
        console.error('[联单] typeCorpInfo 加载失败:', e)
        this.typeCorpInfoData = {}
      }
    },

    /** 查询联单列表（manifestList） */
    async handleQueryManifestList() {
      try {
        const res = await api.manifestList()
        console.log('[联单] manifestList:', res)
        if (res.data) {
          this.manifestListData = Array.isArray(res.data) ? res.data : (res.data.list || [])
          uni.showToast({ title: `查询到${this.manifestListData.length}条联单`, icon: 'success' })
        } else {
          this.manifestListData = []
          uni.showToast({ title: res.message || '暂无联单数据', icon: 'none' })
        }
      } catch (e) {
        console.error('[联单] manifestList 查询失败:', e)
      }
    },

    // ==================== 表单事件 ====================
    /** 选中处置公司 */
    selectTypeCorp(item) {
      this.form.type_corp = item.ctid
      this.form.type_corp_name = item.jydwmc
      this.selectedTypeCorp = item
      this.selectedTypeIndex = this.typeCorpOptions.findIndex(opt => opt.ctid === item.ctid)
      // 选中后自动加载 type_corp_info
      this.loadTypeCorpInfo(item.ctid)
    },

    /** 处置公司 picker change */
    onTypeCorpChange(e) {
      this.selectedTypeIndex = e.detail.value
      const selected = this.typeCorpOptions[e.detail.value]
      this.selectTypeCorp(selected)
    },

    /** 加载经办人列表（handler） */
    async loadHandlers(type) {
      try {
        const res = await api.handler({ type })
        console.log(`[联单] handler(type=${type}):`, res)
        if (res.code === 1000 && res.data) {
          const list = Array.isArray(res.data) ? res.data : (res.data.list || [])
          const options = list.map(item => ({
            value: item.handler_code || item.code || '',
            label: item.handler_name || item.name || item.handler_code || item.code || ''
          }))
          if (type === 3) {
            this.transportHandlerOptions = options
          } else if (type === 4) {
            this.outHandlerOptions = options
          }
        }
      } catch (e) {
        console.error(`[联单] handler(type=${type}) 加载失败:`, e)
      }
    },

    /** 运输经办人 picker change */
    onTransportHandlerChange(e) {
      this.transportHandlerIndex = e.detail.value
      this.form.ysjbr = this.transportHandlerOptions[e.detail.value].value
    },

    /** 出库经办人 picker change */
    onOutHandlerChange(e) {
      this.outHandlerIndex = e.detail.value
      this.form.ckjbr = this.outHandlerOptions[e.detail.value].value
    },

    // ==================== 提交 ====================
    /** 提交联单（manifestCreate） */
    handleSubmit() {
      if (!this.canSubmit) return
      
      api.manifestCreate({
        ctid: this.form.type_corp,
        tcode: '',
        ysjbr: this.form.ysjbr,
        ckjbr: this.form.ckjbr
      }).then(res => {
        console.log('[联单] manifestCreate:', res)
        uni.showToast({ title: '提交成功', icon: 'success' })
      }).catch(e => {
        console.error('[联单] 提交失败:', e)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.readonly {
  color: #999;
}
.form-section{
  padding-bottom: 6px;
  .form-group{
    margin-bottom: 0;
  }
}
.summary-text {
  width: 100%;
  text-align: left;
}
.data-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.data-card-toggle {
  font-size: 12px;
  color: #999;
  font-weight: 400;
}
.data-card-body.collapsed .data-card-row:nth-child(n+4) {
  display: none;
}

.data-card-tag {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
  &.orange {
    background-color: #fff7e6;
    color: #fa8c16;
    border: 1px solid #ffd591;
  }
  &.red {
    background-color: #fff1f0;
    color: #f5222d;
    border: 1px solid #ffa39e;
  }
}
</style>
