<template>
  <view class="page-product-receipt">
    <!--  页面头  -->
    <page-head title="原料填报" />

    <u-form class="form" ref="form" label-width="180rpx">
      <u-form-item label="二维码">
        <u-search placeholder="请扫描二维码" v-model="queryParams.code" @search="search" :show-action="false"></u-search>
      </u-form-item>
    </u-form>

    <u-form class="list" v-if="data.productCode">
      <view class="list-item">
        <lj-list-row label="成品编号:" :value="data.productCode" />
        <lj-list-row label="产品名称:" :value="data.productName" />
        <lj-list-row label="产品登记证号: " :value="data.registrationNo" />
      </view>
    </u-form>

    <u-form class="list" v-else>
      <view class="list-item" style="text-align: center">
        <view>扫码二维码后加载数据</view>
      </view>
    </u-form>

    <scroll-view id="list" scroll-y="true" :style="{ height: listHeight + 'px' }" :lower-threshold="50" v-if="data.productCode">
      <u-form class="list">
        <h3>原药信息<span style="color: #adadad; font-size: 10px">(点击供应商名称可选择供应商)</span></h3>
        <view class="list-item" v-for="(item, index) in data.ingredients" :key="item.ingredientCode">
          <lj-list-row label="原药编码:" :value="item.ingredientCode" />
          <lj-list-row label="原药名称:" :value="item.ingredientName" />

          <view v-if="item.supplierList.length > 0">
            <picker mode="selector" :range="item.supplierList" range-key="supplierName" @change="onPickerChange" class="picker-container" @click="clickGys(index)">
              <view>
                <view v-if="!item.selection"> <span style="color: red"> *</span>供应商： <span style="color: #adadad"> 点击选择供应商 </span></view>
                <view v-else>
                  <lj-list-row label="生产企业:" :value="item.selection.supplierName" />
                  <lj-list-row label="农业登记证号:" :value="item.selection.registrationNo" />
                </view>
              </view>
            </picker>
          </view>
        </view>
      </u-form>
    </scroll-view>

    <!--  按钮  -->
    <view id="button" class="bottom-bar">
      <u-row class="button-bar">
        <u-col :span="12">
          <u-button type="primary" @click="submit">提交</u-button>
        </u-col>
      </u-row>
    </view>
  </view>
</template>

<script lang="ts">
import { Component } from 'vue-property-decorator';
import PageHead from '@/components/lanju/page-head/index.vue';
import { BasePage } from '@/components/base/page';
import LjListRow from '@/components/lanju/lj-list-row/index.vue';
import jPicker from '@/components/J-Picker/jPicker.vue';
import { getIngredientByRegistrationNo, getProductByCode, getSupplierByIngredientCode, productIngredientSupplierSubmit } from '@/pages/mes/RawMaterialForm/model';

class Product {
  productCode: string;
  productName: string;
  registrationNo: string;
  ingredients: Array<Ingredient> = [];
}

class Ingredient {
  ingredientCode: string;
  ingredientName: string;
  supplierList: Array<Supplier> = [];
  selection: Supplier;
}

class Supplier {
  supplierCode: string;
  supplierName: string;
  registrationNo: string;
}

@Component({
  components: { jPicker, LjListRow, PageHead },
})
export default class Index extends BasePage {
  queryParams = {
    code: '',
  };

  data: Product = new Product();

  // 选中的索引
  selectedIndex = 0;

  listHeight = 500;

  async search() {
    //解析code
    const code = this.extractCodeValue(this.queryParams.code);
    this.queryParams.code = code;
    await getProductByCode(code).then(async (res) => {
      if (res.length > 0) {
        this.data = res[0];
        await getIngredientByRegistrationNo(this.data.registrationNo).then(async (res) => {
          if (res.length > 0) {
            this.data.ingredients = res;
            for (const item of res) {
              await getSupplierByIngredientCode(item.ingredientCode).then(async (res) => {
                if (res.length === 1) {
                  item.selection = res[0];
                }
                item.supplierList = res;
              });
            }
            this.$forceUpdate();
            this.getListHeight();
          }
        });
      }
    });
  }

  clickGys(index: any) {
    this.selectedIndex = index;
  }
  onPickerChange(e: any) {
    const index = e.detail.value;
    this.data.ingredients[this.selectedIndex].selection = {
      supplierCode: this.data.ingredients[this.selectedIndex].supplierList[index].supplierCode,
      supplierName: this.data.ingredients[this.selectedIndex].supplierList[index].supplierName,
      registrationNo: this.data.ingredients[this.selectedIndex].supplierList[index].registrationNo,
    };
    this.$forceUpdate();
  }
  submit() {
    const params = [];
    const details = this.data.ingredients;
    if (details && details.length > 0) {
      for (const item of details) {
        if (!item.selection) {
          this.uni.showToast({
            title: '请选择供应商',
            icon: 'none',
            duration: 2000,
          });
          return;
        }
        const obj = {
          productCode: this.data.productCode,
          productName: this.data.productName,
          pRegistrationNo: this.data.registrationNo,
          ingredientCode: item.ingredientCode,
          ingredientName: item.ingredientName,
          supplierCode: item.selection.supplierCode,
          supplierName: item.selection.supplierName,
          iRegistrationNo: item.selection.registrationNo,
        };
        params.push(obj);
      }
    }

    if (params.length <= 0) {
      this.uni.showToast({
        title: '未能获取数据',
        icon: 'none',
        duration: 2000,
      });
      return;
    }
    productIngredientSupplierSubmit({
      products: params,
    }).then(() => {
      this.uni.showToast({
        title: '提交成功',
        icon: 'success',
        duration: 2000,
      });
      setTimeout(() => {
        this.reset();
      }, 1000);
    });
  }
  reset() {
    this.data = new Product();
    this.queryParams.code = '';
    this.$forceUpdate();
  }

  //解析code
  extractCodeValue(str: string) {
    if (!str || typeof str !== 'string') {
      throw new Error('输入的数据为空或不是字符串');
    }
    if (str.length >= 32) {
      let result = str;
      const strArr = str.split('code=');
      if (strArr.length > 1) {
        result = strArr[1];
      }
      if (result.length === 32) {
        return result;
      } else {
        throw new Error('解析失败，请检查数据是否正确');
      }
    } else {
      throw new Error('输入的数据长度不正确');
    }
  }

  getListHeight() {
    //等待页面加载完成
    this.$nextTick(() => {
      let buttonTop = 0;
      //获取底部按钮信息
      const query = uni.createSelectorQuery().in(this);
      query
        .select('#button')
        .boundingClientRect((data) => {
          //获取底部按钮到顶部距离
          buttonTop = data.top;
        })
        .exec();
      //获取列表信息
      query
        .select('#list')
        .boundingClientRect((data) => {
          //获取列表到顶部距离
          const listTop = data.top;
          //
          this.listHeight = buttonTop - listTop - 10;
        })
        .exec();
    });
  }
}
</script>

<style scoped lang="scss">
.form {
  background-color: #fff;
  margin-top: 10px;
  padding: 20rpx;
  border-radius: 10rpx;
  box-shadow: 0 0 20rpx 0 rgba(128, 128, 128, 0.2);

  .u-form-item {
    line-height: 35rpx;
  }
}

.list {
  background-color: #fff;
  margin-top: 20rpx;
  padding: 20rpx 20rpx 25rpx;
  border-radius: 10rpx;
  box-shadow: 0 0 20rpx 0 rgba(128, 128, 128, 0.2);

  .list-item {
    padding: 20rpx;
  }
}

.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  z-index: 99;
  background: #ffffff;
  box-shadow: 0 1rpx 20rpx 0 rgba(128, 128, 128, 0.2);
  padding: 20rpx;
}
</style>
