<template>
  <div class="urgent-purchase-apply-step-container">
    <!-- 申请信息 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>{{ $t('urgentPurchaseApplyStep.applyInfo') }}</span>
      </div>
      <el-form label-width="120px">
        <el-form-item :label="$t('urgentPurchaseApplyStep.warehouse')">
          <el-select v-model="urgentPurchaseApplyStepInfo.shId" @change="_computeFlow" style="width:100%">
            <el-option disabled value="" :label="$t('urgentPurchaseApplyStep.requiredSelectWarehouse')" />
            <el-option v-for="(item, index) in urgentPurchaseApplyStepInfo.storehouses" :key="index" :label="item.shName"
              :value="item.shId" />
          </el-select>
        </el-form-item>

        <el-form-item :label="$t('urgentPurchaseApplyStep.contact')">
          <el-input v-model.trim="urgentPurchaseApplyStepInfo.endUserName"
            :placeholder="$t('urgentPurchaseApplyStep.requiredContact')" />
        </el-form-item>

        <el-form-item :label="$t('urgentPurchaseApplyStep.phone')">
          <el-input v-model.trim="urgentPurchaseApplyStepInfo.endUserTel"
            :placeholder="$t('urgentPurchaseApplyStep.requiredPhone')" />
        </el-form-item>

        <el-form-item :label="$t('urgentPurchaseApplyStep.applyDesc')">
          <el-input type="textarea" v-model.trim="urgentPurchaseApplyStepInfo.description"
            :placeholder="$t('urgentPurchaseApplyStep.requiredDesc')" />
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 采购物品 -->
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <div class="card-header">
          <span>{{ $t('urgentPurchaseApplyStep.purchaseItems') }}</span>
          <el-button type="primary" size="small" @click="_openSelectResourceStoreInfoModel">
            <i class="el-icon-search"></i>
            {{ $t('urgentPurchaseApplyStep.select') }}
          </el-button>
        </div>
      </div>

      <el-table :data="urgentPurchaseApplyStepInfo.resourceStores" border style="width: 100%">
        <el-table-column prop="parentRstName" :label="$t('urgentPurchaseApplyStep.itemType')" align="center">
          <template slot-scope="scope">
            {{ scope.row.parentRstName || '-' }} > {{ scope.row.rstName || '-' }}
          </template>
        </el-table-column>

        <el-table-column prop="resName" :label="$t('urgentPurchaseApplyStep.nameCode')" align="center">
          <template slot-scope="scope">
            {{ scope.row.resName }}({{ scope.row.resCode }})
          </template>
        </el-table-column>

        <el-table-column prop="rssName" :label="$t('urgentPurchaseApplyStep.spec')" align="center">
          <template slot-scope="scope">
            {{ scope.row.rssName || '-' }}
          </template>
        </el-table-column>

        <el-table-column prop="price" :label="$t('urgentPurchaseApplyStep.referencePrice')" align="center" />

        <el-table-column prop="stock" :label="$t('urgentPurchaseApplyStep.stock')" align="center">
          <template slot-scope="scope">
            {{ scope.row.stock }}{{ scope.row.unitCodeName }}
          </template>
        </el-table-column>

        <el-table-column :label="$t('urgentPurchaseApplyStep.applyQuantity')" align="center" width="150">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.quantity" :min="1"
              :placeholder="$t('urgentPurchaseApplyStep.requiredQuantity')" style="width: 80%" />
            {{ scope.row.unitCodeName }}
          </template>
        </el-table-column>

        <el-table-column :label="$t('urgentPurchaseApplyStep.purchasePrice')" align="center" width="150">
          <template slot-scope="scope">
            <el-input-number v-model="scope.row.urgentPrice" :min="0.01"
              :placeholder="$t('urgentPurchaseApplyStep.requiredPrice')" style="width: 100%" />
          </template>
        </el-table-column>

        <el-table-column :label="$t('urgentPurchaseApplyStep.targetWarehouse')" align="center" width="150">
          <template slot-scope="scope">
            <el-select v-model="scope.row.shzId" @change="storeHousesChange($event, scope.$index)" style="width:100%">
              <el-option value="" :label="$t('urgentPurchaseApplyStep.requiredTargetWarehouse')" />
              <el-option v-for="(item, index) in urgentPurchaseApplyStepInfo.storehousesB" :key="index"
                :label="item.shName" :value="item.shId" />
            </el-select>
          </template>
        </el-table-column>

        <el-table-column :label="$t('urgentPurchaseApplyStep.remark')" align="center" width="150">
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" :placeholder="$t('urgentPurchaseApplyStep.optionalRemark')" />
          </template>
        </el-table-column>

        <el-table-column :label="$t('urgentPurchaseApplyStep.operation')" align="center" fixed="right">
          <template slot-scope="scope">
            <el-button type="danger" size="mini" @click="_removeSelectResourceStoreItem(scope.row.resId)">
              <i class="el-icon-delete"></i>
              {{ $t('urgentPurchaseApplyStep.remove') }}
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <div class="footer-buttons">
      <el-button type="primary" @click="_finishStep">
        {{ $t('urgentPurchaseApplyStep.submit') }}
      </el-button>
    </div>

    <choose-resource-store4 ref="chooseResourceStore4" @setSelectResourceStores="handleSetSelectResourceStores" />
  </div>
</template>

<script>
import { getCommunityId } from '@/api/community/communityApi'
import ChooseResourceStore4 from '@/components/resource/chooseResourceStore4'
import * as api from '@/api/resource/urgentPurchaseApplyStepApi'
import {getUserName,getUserTel} from '@/api/user/userApi'

export default {
  name: 'UrgentPurchaseApplyStepList',
  components: {
    ChooseResourceStore4
  },
  data() {
    return {
      urgentPurchaseApplyStepInfo: {
        resourceStores: [],
        description: '',
        endUserName: '',
        endUserTel: '',
        file: '',
        resOrderType: '',
        staffId: '',
        shId: '',
        staffName: '',
        communityId: '',
        storehouses: [],
        storehousesB: []
      }
    }
  },
  created() {
    this._initData()
  },
  methods: {
    async _initData() {
      this.urgentPurchaseApplyStepInfo.communityId = await getCommunityId()
      this.urgentPurchaseApplyStepInfo.resOrderType = this.$route.query.resOrderType
      this.urgentPurchaseApplyStepInfo.endUserName = getUserName()
      this.urgentPurchaseApplyStepInfo.endUserTel = getUserTel()
      this._listAllocationStorehouse()
      this._listAllocationStorehouseB()
    },
    async _listAllocationStorehouse() {
      try {
        const params = {
          page: 1,
          row: 100,
          allowPurchase: 'ON'
        }
        const { data } = await api.listStorehouses(params)
        this.urgentPurchaseApplyStepInfo.storehouses = data
      } catch (error) {
        console.error('获取仓库列表失败:', error)
      }
    },
    async _listAllocationStorehouseB() {
      try {
        const params = {
          page: 1,
          row: 100,
          communityId: this.urgentPurchaseApplyStepInfo.communityId
        }
        const { data } = await api.listStorehouses(params)
        this.urgentPurchaseApplyStepInfo.storehousesB = data
      } catch (error) {
        console.error('获取目标仓库列表失败:', error)
      }
    },
    _openSelectResourceStoreInfoModel() {
      if (!this.urgentPurchaseApplyStepInfo.shId) {
        this.$message.error(this.$t('urgentPurchaseApplyStep.requiredSelectWarehouse'))
        return
      }
      if (!this.urgentPurchaseApplyStepInfo.endUserName) {
        this.$message.error(this.$t('urgentPurchaseApplyStep.requiredContact'))
        return
      }
      if (!this.urgentPurchaseApplyStepInfo.endUserTel) {
        this.$message.error(this.$t('urgentPurchaseApplyStep.requiredPhone'))
        return
      }
      if (!this.urgentPurchaseApplyStepInfo.description) {
        this.$message.error(this.$t('urgentPurchaseApplyStep.requiredDesc'))
        return
      }
      this.$refs.chooseResourceStore4.open({
        shId: this.urgentPurchaseApplyStepInfo.shId
      })
    },
    handleSetSelectResourceStores(resourceStores) {
      let oldList = this.urgentPurchaseApplyStepInfo.resourceStores
      // 过滤重复选择的商品
      resourceStores.forEach((newItem, newIndex) => {
        newItem.rsId = ''
        newItem.shzId = ''
        oldList.forEach((oldItem) => {
          if (oldItem.resId === newItem.resId) {
            delete resourceStores[newIndex]
          }
        })
      })
      // 合并已有商品和新添加商品
      resourceStores.push.apply(resourceStores, oldList)
      // 过滤空元素
      resourceStores = resourceStores.filter((s) => {
        return s['resId']
      })
      this.urgentPurchaseApplyStepInfo.resourceStores = resourceStores
    },
    _resourcesFromSameHouse(resourcesList) {
      if (!resourcesList || resourcesList.length < 2) {
        return true
      }
      let lastHouse = ''
      let sign = true
      for (let i = 0; i < resourcesList.length; i++) {
        if (lastHouse === '') {
          lastHouse = resourcesList[i].shId
          continue
        }
        if (lastHouse === resourcesList[i].shId) {
          continue
        } else {
          sign = false
          break
        }
      }
      return sign
    },
    async _finishStep() {
      const _resourceStores = this.urgentPurchaseApplyStepInfo.resourceStores
      if (!_resourceStores || _resourceStores.length < 1) {
        this.$message.error(this.$t('urgentPurchaseApplyStep.requiredSelectItems'))
        return
      }
      if (!this._resourcesFromSameHouse(_resourceStores)) {
        this.$message.error(this.$t('urgentPurchaseApplyStep.sameWarehouseRequired'))
        return
      }
      let _saveFlag = true
      _resourceStores.forEach(item => {
        if (!item.shzId) {
          this.$message.error(`${item.resName}${this.$t('urgentPurchaseApplyStep.requiredTargetWarehouse')}`)
          _saveFlag = false
          return
        }
        if (!item.quantity || item.quantity <= 0) {
          this.$message.error(`${item.resName}${this.$t('urgentPurchaseApplyStep.requiredQuantity')}`)
          _saveFlag = false
          return
        }
        if (!item.urgentPrice || item.urgentPrice <= 0) {
          this.$message.error(`${item.resName}${this.$t('urgentPurchaseApplyStep.requiredPrice')}`)
          _saveFlag = false
          return
        }
      })
      if (!_saveFlag) {
        return
      }
      try {
        const res = await api.urgentPurchaseApply(this.urgentPurchaseApplyStepInfo)
        if (res.code === 0) {
          this.$message.success(this.$t('common.operationSuccess'))
          this.$router.go(-1)
        } else {
          this.$message.error(res.msg)
        }
      } catch (error) {
        console.error('提交失败:', error)
        this.$message.error(this.$t('common.operationFailed'))
      }
    },
    storeHousesChange(e, i) {
      const shId = e
      this.urgentPurchaseApplyStepInfo.storehouses.forEach((item) => {
        if (item.shId === shId) {
          this.urgentPurchaseApplyStepInfo.resourceStores[i].shzName = item.shName
        }
      })
    },
    _removeSelectResourceStoreItem(resId) {
      this.urgentPurchaseApplyStepInfo.resourceStores.forEach((item, index) => {
        if (item.resId === resId) {
          this.urgentPurchaseApplyStepInfo.resourceStores.splice(index, 1)
        }
      })
    },
    _computeFlow() {
      this.urgentPurchaseApplyStepInfo.resourceStores = []
    }
  }
}
</script>

<style lang="scss" scoped>
.urgent-purchase-apply-step-container {
  padding: 20px;

  .box-card {
    margin-bottom: 20px;

    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
    }
  }

  .footer-buttons {
    text-align: right;
    margin-top: 20px;
  }
}
</style>