<template>
	<view class="container">

    <view class="example">
      <uni-forms ref="customForm" :rules="customRules" labelWidth="60px" :modelValue="formData">
        <uni-forms-item label="制浆线" required name="feedingPipeline">
          <uni-data-checkbox v-model="formData.feedingPipeline" :localdata="pipelineTypes()" />
        </uni-forms-item>
        <uni-forms-item label="投料类型" required name="feedingType">
          <uni-data-checkbox v-model="formData.feedingType" :localdata="feedingTypes()" @change="handleTypeChange"/>
        </uni-forms-item>
        <uni-forms-item v-if="formData.feedingType==='wet' || formData.feedingType==='dry'" label="重量/kg"  name="weight">
          <uni-easyinput type="number" v-model="formData.weight" placeholder="" />
        </uni-forms-item>
        <uni-forms-item label="备注"  name="remark">
          <uni-easyinput v-model="formData.remark" placeholder="" />
        </uni-forms-item>
        <uni-group title="card 模式" mode="card" v-for="(item,index) in formData.feedingRecordDetails" :key="item.id"
                   :name="['feedingRecordDetails',index,'value']">
          <template v-slot:title>
            <view class="uni-group-title">
              <uni-row>
                <uni-col :span="18">
                  <uni-forms-item  label="原料" required name="itemId">
                    <uni-data-select placement="top" v-model="formData.feedingRecordDetails[index].itemId" :localdata="itemList"></uni-data-select>
                  </uni-forms-item>
                </uni-col>
                <uni-col :span="6" align="center">
                  <uni-icons type="trash" size="25" color="red" @click="del(item.id)"></uni-icons>
                </uni-col>
              </uni-row>
            </view>
          </template>
          <uni-forms-item  label="单位" required name="unitId">
            <uni-data-select v-model="formData.feedingRecordDetails[index].unitId" :localdata="unitList"></uni-data-select>
          </uni-forms-item>
          <uni-forms-item label="数量" required name="weight">
            <uni-easyinput type="number" v-model="formData.feedingRecordDetails[index].weight"/>
          </uni-forms-item>

        </uni-group>
      </uni-forms>
      <view class="button-group">
        <button v-if="formData.feedingType==='org'" type="primary" size="mini" @click="add">
          <uni-icons type="plus" size="15"></uni-icons>
          添加原料
        </button>
        <button type="primary" size="mini" @click="submit('customForm')">保存</button>
      </view>
    </view>
	</view>
</template>

<script>
import {create} from "@/api/mes/record"
import {getUnitList,getItemList} from "@/api/mes/product"
import { pipelineTypes,feedingTypes, findTextByValue} from "@/api/system/dict/data";
import {showConfirm} from "@/utils/common";
import tab from "@/plugins/tab";
import modal from "@/plugins/modal";
export default {
  components: {},
  data() {
    return {
      // 自定义表单数据
      formData: {
        id: undefined,
        feedingPipeline: undefined,
        feedingType: undefined,
        weight: 0,
        remark: undefined,
        feedingRecordDetails: []
      },
      // 自定义表单校验规则
      customRules: {
        feedingPipeline: {rules: [{required: true, errorMessage: '姓名不能为空'}]},
        feedingType: {rules: [{required: true, errorMessage: '工位不能为空'}]},
        feedingRecordDetails: {rules: [
            {format: 'array', errorMessage: '产品列表格式错误'},
            {validateFunction: function(rule, value, data, callback) {
              if (value.length < 2) {
                callback('产品信息不能为空')
              }
              return true
            }
          }]
        }
      },
      itemList:[],
      unitList:[]
    }
  },
  computed: {
  },
  onLoad() {
    this.getItemList()
  },
  onReady() {
    // 设置自定义表单校验规则，必须在节点渲染完毕后执行
    this.$refs.customForm.setRules(this.customRules)
  },
  methods: {
    pipelineTypes() {return pipelineTypes},
    feedingTypes() {return feedingTypes},
    submit(ref) {
      this.$refs[ref].validate().then(res => {
        var ok = 1;
        if(this.formData.feedingRecordDetails && this.formData.feedingRecordDetails.length > 0) {
          for (let i = 0; i < this.formData.feedingRecordDetails.length; i++) {
            if(!this.formData.feedingRecordDetails[i].itemId || this.formData.feedingRecordDetails[i].itemId===''
             || !this.formData.feedingRecordDetails[i].weight|| this.formData.feedingRecordDetails[i].weight <= 0) {
              ok = 0;
              uni.showToast({
                title: `原料信息不能为空！`,
                icon: 'error'
              })
              break;
            }
          }
        }
        if(ok===1){
          showConfirm("确认保存投料记录单吗？").then(res => {
            if (res.confirm) {
              create(this.formData).then(response => {
                modal.msgSuccess("保存成功")
                tab.navigateBack()
              })
            }
          })
        }
      }).catch(err => {
        console.log('err', err);
      })
    },
    handleTypeChange(e){
      this.formData.feedingType =e.detail.value;
      if(this.formData.feedingType === 'wet' || this.formData.feedingType==='dry'){
        this.formData.feedingRecordDetails = []
      }
    },
    getItemList() {
      getItemList().then(response => {
        this.itemList = response.data;
      })
      getUnitList().then(response => {
        this.unitList = response.data;
      })
    },
    add() {
      this.formData.feedingRecordDetails.push({
        id: Date.now(),
        itemId: undefined,
        unitId: 3,
        weight: 0
      })
    },
    del(id) {
      let index = this.formData.feedingRecordDetails.findIndex(v => v.id === id)
      this.formData.feedingRecordDetails.splice(index, 1)
    }
  }
}
</script>

<style lang="scss">
	.example {
		padding: 15px;
		background-color: #fff;
	}

  .button-group {
    margin-top: 15px;
    display: flex;
    justify-content: space-around;
  }

  .button {
    display: flex;
    align-items: center;
    height: 35px;
    line-height: 35px;
    margin-left: 10px;
  }
  .uni-group-title{
    padding-top: 5px;
    background-color: #f4c7c7;
  }
</style>
