
<template>
    <layout-form>
        <el-form :model="form" :loading="loading" :rules="rules" size='small' label-width='100px' ref="form">
            <el-row>
                <Field label="资产码" prop="assetNum" v-model="form.assetNum" :disabled="pageInfo.type !== 'add'" placeholder="新增后不可修改"/>
                <Field label="业务码" prop="deviceNum" v-model="form.deviceNum" :disabled="pageInfo.type == 'view'"/>
<!--              <Field label="所属bom" prop="bomId" v-model="form.bomId">
                <el-select v-model="form.bomId" filterable clearable remote :remote-method="bomRemote"
                           :disabled = "pageInfo.type == 'view'" placeholder="请输入物料"  @focus="focusBom" @change="bomChange">
                  <el-option v-for="item in bomData" :key="item.id" :label="item.name" :value-key="item" :value="item.id"></el-option>
                </el-select>
              </Field>-->

              <Field   label="BOM版本" prop="bomName" :span="24" >
                <el-input v-model="form.bomName" disabled="" >
                  <el-button slot="append" type="success" @click.prevent="selectCategory" :disabled="pageInfo.type == 'view' || (pageInfo.type == 'edit' && form.bomId != null)">选择产品BOM版本</el-button>
                </el-input>
              </Field>
<!--              <el-col>
                <el-form-item label="BOM版本" prop="bomName">
                  <el-input v-model="form.bomName" disabled="">
                    <el-button slot="append" type="success" @click.prevent="selectCategory" :disabled="pageInfo.type == 'view' || (pageInfo.type == 'edit' && form.bomId != null)">选择产品BOM版本</el-button>
                  </el-input>
                </el-form-item>
              </el-col>-->


<!--                <Field label="所属物料" prop="materiaId" v-model="form.materiaId" disabled>
                    <el-select v-model="form.materiaId" filterable clearable remote :remote-method="materiaRemote"
                               :disabled = "pageInfo.type == 'view'" placeholder="请输入物料" @focus="focusMateria" disabled>
                        <el-option v-for="item in materiaData" :key="item.id" :label="item.name" :value-key="item" :value="item.id"></el-option>
                    </el-select>
                </Field>-->

<!--                <Field label="所属物料码" prop="materiaId" v-model="form.materiaCode" disabled/>-->
              <Field  label="生产成本" prop="produceCost" >
                <el-input v-model="produceCost" min="0" placeholder="请输入金额" :disabled="pageInfo.type == 'view'"> <template slot="append">元</template></el-input>
              </Field>

              <Field label="生产厂家" prop="producerId" v-model="form.producerId" :disabled="pageInfo.type == 'view'">
                <el-select v-model="form.producerId" filterable clearable remote :remote-method="producerRemote"
                           :disabled = "pageInfo.type == 'view'" @focus="focusProducer" placeholder="请输入厂家" >
                  <el-option v-for="item in producerData" :key="item.id" :label="item.name" :value="item.id"></el-option>
                </el-select>
              </Field>


                <Field label="生产日期" prop="produceDate" v-model="form.produceDate" type="date" :disabled="pageInfo.type == 'view'"/>
                <Field label="流转状态" prop="flowStatus" v-model="form.flowStatus" :enumData='dict.flowStatus' type='select' disabled/>
                <Field label="是否启用" prop="enabled" v-model="form.enabled" :enumData='dict.enabled' type='select' :disabled="pageInfo.type != 'add'"/>
            </el-row>

          <el-dialog title="产品BOM" :visible.sync="bomDirDialog.visible" width="50%">
            <div class="mytree">
              <el-tree ref="bomTree" :data="data" id="el-tree" node-key="id" :props="treeProps" :load="loadNode" highlight-current lazy :render-content="renderContent" @node-click="handleNodeClick">
              </el-tree>
            </div>
          </el-dialog>

          <form-buttons @submit='submitForm' v-if="pageInfo.type != 'view'" />
          <el-button @click="$router.go(-1)" size='small' icon='el-icon-circle-close-outline' v-if="pageInfo.type == 'view'">返回</el-button>

        </el-form>
    </layout-form>
</template>

<script>
import form from "@/assets/mixins/form";
import {normalCallPost} from '@/assets/utils/index';
export default {
    mixins: [form],
    data() {
        return {
            produceCost: "",//生产成本
            bomDirDialog: {
              visible: false,
            },
            data: [],
            tree: [],
            form: {},
          treeProps: {
            children: "children",
            label: "name",
            isLeaf: "isLeaf",
            type: "type",
            icon: "icon",
            bomId: "bomId",
            id: "id",
          },

            materiaData:[],
            bomData:[],
            producerData:[],
            toString: ["flowStatus", "enabled"],
            rules: {
                assetNum: [
                    {
                        required: true,
                        message: "请输入资产码",
                        trigger: "blur",
                    },
                  {
                    max: 16,
                    message: "请输入16位资产码",
                    trigger: "blur",
                  },
                  {
                    min: 16,
                    message: "请输入16位资产码",
                    trigger: "blur",
                  },
                ],
                bomName: [
                    {
                        required: true,
                        message: "请选择所属BOM版本",
                        trigger: "blur",

                    },
                ],
              producerId: [
                {
                  required: true,
                  message: "请选择生产厂家",
                  trigger: "blur",
                },
              ],
                produceDate: [
                    {
                      required: true,
                        message: "请输入生产日期",
                        trigger: "blur",
                    },
                ],
              produceCost1: [
                    {
                        required: true,
                        message: "请输入生产成本",
                        trigger: "blur",

                    },
                ],
              produceCost:[{ validator: (rule, value, callback) => {
                  if(this.produceCost == null || this.produceCost === ""){
                    callback(new Error('生产成本不能为空'));
                  }
                  let pattern = /^\d+.?\d{0,2}$/;
                  if (!pattern.test(this.produceCost)) {
                    callback(new Error("请输入整数或2位小数"))
                  }
                  return callback();
                }, trigger: "blur", required: true, }],
                flowStatus: [
                    {
                        required: true,
                        message: "请选择流转状态",
                        trigger: "blur",
                    },
                ],
                enabled: [
                    {
                        required: true,
                        message: "请选择是否启用",
                        trigger: "blur",
                    },
                ],
            },
        };
    },
    methods:{

        beforeRender(data) {
            if(data.entity.produceDate){
              data.entity.produceDate = new Date(data.entity.produceDate);
            }
            if(data.entity.produceCost){
              this.produceCost = ((data.entity.produceCost || 0) / 1000).toFixed(2)
            }
            this.loadMateria(data);
            this.loadBom(data);
            this.loadProducer(data);
            return data;
        },
        beforeSubmit(form){
            //元转成厘提交
            if(this.produceCost){
              this.form.produceCost =  ((this.produceCost || 0) * 1000).toFixed(0);
            }
          return this.form;
        },

      selectCategory() {
        this.bomDirDialog.visible = true;
        this.$nextTick(() => {
          this.$post("/materia/bom/tree/getBomVersionListByParentId", {
            parentId: -1,
            type: 0,
          }).then(({ data }) => {
            this.data = data.result;
          });
        });
      },
      async loadNode(node, resolve) {
        console.log("1111");
        console.log(node);

        if (node.level === 0) {
          return;
        }

        //   if (node.data.type === 1) {
        //     resolve(node.data.children);
        //     return;
        //   } else if (node.data.type == 2) {
        //     //物料
        //   }
        this.$post("/materia/bom/tree/getBomVersionListByParentId", {
          parentId: node.data.id,
          type: node.data.type,
        }).then(({ data }) => {
          resolve(data.result);
        });
      },
      handleNodeClick(data, node, obj) {
        this.node = node;
        let type = data.type;
        console.log("type=" + type);
        console.log(type === 1);
        if (type === 1) {

          this.form = {
            ...this.form,
            bomId: data.bomId,
            bomCode: data.bomCode,
            bomName: data.name
          }
          this.bomDirDialog.visible = false;
        }
      },
      renderContent: function (h, { node, data, store }) {
        return (
            <span>
                    <i
                        style="font-size:16px;color:#409EFF"
                        class={data.icon}
                    ></i>
                    <span style="padding-left: 2px;font-size:14px">
                        {node.label}
                    </span>
                </span>
        );
      },

        //回显物料
        async loadMateria(data) {
            if(data.entity.id){
                const query = {'pageInfo.prePageResult': -1, 'query.id': data.entity.materiaId};
                this.materiaData = await this.getMateriaListByQuery(query);
               /* if(selectList.length > 0){
                    this.selectMateria = selectList[0];
                }*/
            }

        },
      async focusMateria(){
        if(this.bomData.length != 10){
          const query = {'pageInfo.prePageResult': 10};
          this.materiaData = await this.getMateriaListByQuery(query);
        }
      },

        //物料远程搜索
        async materiaRemote(name){
            if(!name.match(/^[ ]*$/)){
                const query = {'pageInfo.prePageResult': -1, 'query.name': '%'+name+'%'};
                this.materiaData = await this.getMateriaListByQuery(query);
            }else{
                this.materiaData = [];
            }
        },
        //物料查询
        async getMateriaListByQuery(query){
            try {
                const data = await normalCallPost('/materia/list', query);
                const list = data.data.result.map(({ id, name, code }) => {
                    return { id, name, code }
                });
                return list;
            } catch (error) {
                return [];
            }
        },


      //回显BOM
      async loadBom(data) {
        if(data.entity.bomId){
          const query = {'pageInfo.prePageResult': -1, 'query.id': data.entity.bomId};
          this.bomData = await this.getBomListByQuery(query);
          /* if(selectList.length > 0){
               this.selectMateria = selectList[0];
           }*/
          let showName = '[' + this.bomData[0].code + ']' + this.bomData[0].materiaName + '【版本：' + this.bomData[0].version +"】";
          this.form.bomName = showName;
          this.form.bomId = data.entity.bomId;
        }

      },

      async focusBom(){
        if(this.bomData.length != 10){
          const query = {'pageInfo.prePageResult': 10};
          this.bomData = await this.getBomListByQuery(query);
        }
      },

      //BOM远程搜索
      async bomRemote(name){
        if(!name.match(/^[ ]*$/)){
          const query = {'pageInfo.prePageResult': -1, 'query.name': '%'+name+'%'};
          this.bomData = await this.getBomListByQuery(query);
        }else{
          this.bomData = [];
        }
      },
      //bom查询
      async getBomListByQuery(query){
        try {
          const data = await normalCallPost('/materia/bom/list', query);
          const list = data.data.result.map(({ id, materiaName, code, materiaId,version }) => {
            return { id, materiaName, code, materiaId,version }
          });
          console.log(list);
          return list;
        } catch (error) {
          return [];
        }
      },
      bomChange(data){

      },

    //回显生产厂家
      async loadProducer(data) {
        if(data.entity.producerId){
          const query = {'pageInfo.prePageResult': -1, 'query.id': data.entity.producerId};
          this.producerData = await this.getSupplierListByQuery(query);
          /* if(selectList.length > 0){
               this.selectMateria = selectList[0];
           }*/
        }

      },
      async focusProducer(){
        if(this.producerData.length != 10){
          const query = {'pageInfo.prePageResult': 10};
          this.producerData = await this.getSupplierListByQuery(query);
        }
      },
      async producerRemote(name){
        if(!name.match(/^[ ]*$/)){
          const query = {'pageInfo.prePageResult': -1, 'query.name': name};
          this.producerData = await this.getSupplierListByQuery(query);
        }else{
          this.producerData = [];
        }
      },

      async getSupplierListByQuery(query){
        try {
          const data = await normalCallPost('/supplier/list', query);
          const list = data.data.result.map(({ id, name }) => {
            return { id, name }
          });
          return list;
        } catch (error) {
          return [];
        }
      }

    }
};
</script>
