<template>
  <div class="page-body">
    <vxe-pulldown ref="pulldownRef" transfer>
      <template #default>
        <vxe-input ref="inputx" style="width:400px" v-model="searchName" suffix-icon="vxe-icon-table"
          placeholder="搜索员工，随车联，工序等信息" @keydown="keydownEvent" @suffix-click="suffixClick"></vxe-input>
        <a-icon type="scan" :style="{ fontSize: '22px', color: '#08c', marginLeft: '10px' }" @click="inputFocus" />
      </template>
      <template #dropdown>
        <div class="search-dropdown">
          <div class="search-dropdown-column">
            <h3>随车联</h3>
            <vxe-grid border auto-resize height="400" :row-config="{ isHover: true }" :loading="loading"
              :data="tableDataOrders" :columns="tableColumnOrders" @cell-click="cellClickEventOrders">
            </vxe-grid>
          </div>
          <div class="search-dropdown-column">
            <h3>员工</h3>
            <vxe-grid border auto-resize height="400" :row-config="{ isHover: true }" :loading="loading"
              :data="tableDataStaff" :columns="tableColumn" @cell-click="cellClickEventStaff">
            </vxe-grid>
          </div>
          <div class="search-dropdown-column">
            <h3>工序</h3>
            <vxe-grid border auto-resize height="400" :row-config="{ isHover: true }" :loading="loading"
              :data="tableDataProcesses" :columns="tableColumn" @cell-click="cellClickEventProcesses">
            </vxe-grid>
          </div>
        </div>
      </template>
    </vxe-pulldown>

    <div class="container">
      <div class="left">
        <div class="card">
          <h4>随车联(工序流转卡)信息</h4>
          <vxe-form :data="formOptions4.data" ref="xForm" :title-width="formOptions4.titleWidth"
            :title-align="formOptions4.titleAlign" :rules="formOptions4.rules" :items="formOptions4.items" titleColon>
          </vxe-form>
        </div>

        <div class="card">
          <h4>报工信息</h4>

          <vxe-form :data="formOptions.data" ref="xForm" :title-width="formOptions.titleWidth"
            :title-align="formOptions.titleAlign" :rules="formOptions.rules" :items="formOptions.items" titleColon>
          </vxe-form>
        </div>
      </div>
      <div class="right">

        <div class="card">
          <h4>员工信息</h4>
          <vxe-form :data="formOptions2.data" ref="xForm" :title-width="formOptions2.titleWidth"
            :title-align="formOptions2.titleAlign" :rules="formOptions2.rules" :items="formOptions2.items" titleColon>
          </vxe-form>
        </div>

        <div class="card">
          <h4>工序信息</h4>

          <vxe-form :data="formOptions3.data" ref="xForm" :title-width="formOptions3.titleWidth"
            :title-align="formOptions3.titleAlign" :rules="formOptions3.rules" :items="formOptions3.items" titleColon>
          </vxe-form>
        </div>


      </div>
    </div>

    <a-button type="primary" @click="save" style="margin-top: 10px;">确定报工</a-button>

  </div>
</template>

<script>
import BASE_URL from '@/services/mes/api.js';
const settings = require('../../basic/settings.js');

import JSONbig from 'json-bigint'
export default {

  name: '',
  components: {},
  props: {
    pageMode: {
      type: String,
      default: "edit"
    },
    dataId: {
    }

  },

  data() {


    let getEnumActionParams = (enum_id) => {
      return {
        "ptyid": 0,
        "company_id": 1,
        "enum_id": this.$mk.toBigInt(enum_id),
        "search_rules": [
        ],
        "end_time": 0,
        "company_token": process.env.VUE_APP_COMPANYTOKEN,
        "store_id": 0,
        "order_bys": [
        ],
        "limit": 0,
        "project_token": process.env.VUE_APP_APPTOKEN,
        "beid": 1,
        "page": 1,
        "start_time": 0
      };

    }



    var pageData = {

      actions: {
      },

      keyName: 'id',
      // 是否编辑模式
      isEdit: false,


      formOptions4: {
        data: {
        },
        // 标题宽度
        titleWidth: 100,
        // 标题对齐方式
        titleAlign: 'right',
        // 表单校验规则
        rules: {
        },
        // 表单项
        items: [

          {
            title: '左侧',
            span: 9,
            children: [
              { field: '布产单信息', title: '布产单信息', span: 24, titleColon: false, className: 'formtitle' },
              { field: 'production_number', title: '布产单号', span: 24, itemRender: { name: 'MkFormInputShow' } },
              { field: 'production_department_name', title: '布产部门', span: 24, itemRender: { name: 'MkFormInputShow' } },
              { field: '布产类型', title: '布产类型', span: 24, itemRender: { name: 'MkFormInputShow' } },
              { field: '是否补单', title: '是否补单', span: 24, itemRender: { name: 'MkFormInputShow' } },
              { field: '补单原因', title: '补单原因', span: 24, itemRender: { name: 'MkFormInputShow' } },

            ],
          },
          {
            title: '中侧',
            span: 9,
            children: [
              { field: '料品信息', title: '料品信息', span: 24, titleColon: false, className: 'formtitle' },
              { field: 'materials_code', title: '料品编号', span: 24, itemRender: { name: 'MkFormInputShow' } },
              { field: 'materials_name', title: '料品名称', span: 24, itemRender: { name: 'MkFormInputShow' } },

            ],
          },
          {
            title: '右侧',
            span: 6,
            children: [
              {
                field: 'image', span: 24, itemRender: {
                  name: 'MkFormCropper', props: {
                    isReadonly: true
                  }
                }
              },
            ],
          },
          {
            title: '下侧',
            span: 24,
            children: [
              { field: '料品信息', title: '随车联信息', span: 24, titleColon: false, className: 'formtitle' },
              { field: 'batch_no', title: '随车联号', span: 6, itemRender: { name: 'MkFormInputShow' } },
              { field: 'number', title: '数量', span: 6, itemRender: { name: 'MkFormInputShow' } },
              { field: 'is_pick', title: '是否领料', span: 6, itemRender: { name: 'MkFormInputShow', props: { params: { dataType: 'yesorno' } } } },
              { field: 'start_time', title: '开始时间', span: 6, itemRender: { name: 'MkFormInputShow', props: { params: { dataType: 'datetime' } } } },
              { field: 'work_type', title: '计工方式', span: 6, itemRender: { name: 'MkFormInputShow' } },
              { field: 'car_code', title: '车号', span: 6, itemRender: { name: 'MkFormInputShow' } },
              { field: 'pick_time', title: '领料时间', span: 6, itemRender: { name: 'MkFormInputShow', props: { params: { dataType: 'datetime' } } } },
              { field: 'status', title: '状态', span: 6, itemRender: { name: 'MkFormInputShow' } },
            ],
          },




        ]
      },

      formOptions2: {
        data: {
        },
        // 标题宽度
        titleWidth: 100,
        // 标题对齐方式
        titleAlign: 'right',
        // 表单校验规则
        rules: {
        },
        // 表单项
        items: [
          {
            span: 6,
            children: [
              {
                field: 'avatar', span: 24, itemRender: {
                  name: 'MkFormCropper', props: {
                    isReadonly: true
                  }
                }
              },
            ],
          },
          {
            span: 18,
            children: [

              { field: 'name', title: '姓名', span: 24, itemRender: { name: 'MkFormInputShow' } },
              { field: 'code', title: '工号', span: 24, itemRender: { name: 'MkFormInputShow' } },
              { field: 'phone', title: '电话', span: 24, itemRender: { name: 'MkFormInputShow' } },
              { field: 'processName', title: '工序', span: 24, itemRender: { name: 'MkFormInputShow' } },
            ],
          },

        ]
      },


      formOptions3: {
        data: {
        },
        // 标题宽度
        titleWidth: 100,
        // 标题对齐方式
        titleAlign: 'right',
        // 表单校验规则
        rules: {
        },
        // 表单项
        items: [
          { field: 'name', title: '工序名称', span: 24, itemRender: { name: 'MkFormInputShow' } },
          { field: 'code', title: '工序编号', span: 24, itemRender: { name: 'MkFormInputShow' } },

        ]
      },


      formOptions: {
        data: {
        },
        // 标题宽度
        titleWidth: 110,
        // 标题对齐方式
        titleAlign: 'right',
        // 表单校验规则
        rules: {
        },
        // 表单项
        items: [ 
        {
            title: '工艺类型', span: 8,
            field: 'technology_type',
            itemRender: {
              name: 'MkFormDataSelector', props: {
                params: {
                  dataType: "string",
                  valueField: "name",
                  textField: "name",
                  listdataFieldName: 'enum_value',
                  actionParams: getEnumActionParams(settings.enum_ids.工艺类型),
                  dataUrl: `${BASE_URL.BASE_URL}/MesReporting/Get/TouchScreen/v1/mes/reporting/touchScreen/getEnum`
                }
              }
            },
          }, 
          {
            title: '成型方式', span: 8,
            field: 'molding_type',
            itemRender: {
              name: 'MkFormDataSelector', props: {
                params: {
                  dataType: "string",
                  valueField: "name",
                  textField: "name",
                  listdataFieldName: 'enum_value',
                  actionParams: getEnumActionParams(settings.enum_ids.成型方式),
                  dataUrl: `${BASE_URL.BASE_URL}/MesReporting/Get/TouchScreen/v1/mes/reporting/touchScreen/getEnum`
                }
              }
            },
          },
          

          {
            title: '查坯方式', span: 8,
            field: 'embryo_type',
            itemRender: {
              name: 'MkFormDataSelector', props: {
                params: {
                  dataType: "string",
                  valueField: "name",
                  textField: "name",
                  listdataFieldName: 'enum_value',
                  actionParams: getEnumActionParams(settings.enum_ids.查坯方式),
                  dataUrl: `${BASE_URL.BASE_URL}/MesReporting/Get/TouchScreen/v1/mes/reporting/touchScreen/getEnum`
                }
              }
            },
          },
          {
            title: '花面', span: 8,
            field: 'flower_type',
            itemRender: {
              name: 'MkFormDataSelector', props: {
                params: {
                  dataType: "string",
                  valueField: "name",
                  textField: "name",
                  listdataFieldName: 'enum_value',
                  actionParams: getEnumActionParams(settings.enum_ids.花面),
                  dataUrl: `${BASE_URL.BASE_URL}/MesReporting/Get/TouchScreen/v1/mes/reporting/touchScreen/getEnum`
                }
              }
            },
          }, 
          { field: 'loss_number', title: '报损数量', span: 8, itemRender: { name: '$input', props: { type: 'number' } } },
          { field: 'loss_staff_name', title: '损耗人员', span: 8, itemRender: { name: '$input', props: {  } } },
          { field: 'loss_remark', title: '损耗备注', span: 8, itemRender: { name: '$input', props: {  } } },

          
          
          {
            title: '土质', span: 8,
            field: 'soil_type',
            itemRender: {
              name: 'MkFormDataSelector', props: {
                params: {
                  dataType: "string",
                  valueField: "name",
                  textField: "name",
                  listdataFieldName: 'enum_value',
                  actionParams: getEnumActionParams(settings.enum_ids.土质),
                  dataUrl: `${BASE_URL.BASE_URL}/MesReporting/Get/TouchScreen/v1/mes/reporting/touchScreen/getEnum`
                }
              }
            },
          },
          { field: 'soil_date', title: '土质日期', span: 8, itemRender: { name: '$input', props: { type: 'date' } } },
          { field: 'remark', title: '备注', span: 24, itemRender: { name: '$input', props: {   } } },


          
        ]
      },


      searchName: '',
      lastTriggerTime: null,
      lastScanTime: null,

      loading: false,
      tableColumnOrders: [
        { field: 'production_number', title: '单号' },
        { field: 'materials_name', title: '料品名' },
      ],
      tableColumn: [
        { field: 'name', title: '名称' },

        { field: 'code', title: '编号' }
      ],
      tableDataStaff: [],
      tableDataProcesses: [],
      tableDataOrders: []

    };


    // 合并表单数据及配置
    pageData.formOptions = Object.assign({}, this.$mk.config.defaults.formOptions, pageData.formOptions);

    return pageData;
  },

  computed: {

  },


  created() {

    setTimeout(() => {
      this.$refs.inputx.focus();

    }, 200)

    //149433255169363968
    //this.loadStaff({id:"149433255169363968"})
  },
  // 函数
  methods: {

    inputFocus() {
      this.$refs.inputx.focus();
    },

    doLoadData() {

      const now = Date.now();
      if (this.lastTriggerTime) {
        const elapsedTime = now - this.lastTriggerTime;
        if (elapsedTime < 1000) {
          return;
        }
      }

      const $pulldown = this.$refs.pulldownRef
      if ($pulldown) {
        $pulldown.showPanel()
      }
      this.lastTriggerTime = now;
      this.loadData({ key: this.searchName })

    },

    loadData({ key }) {

      this.loading = true
      this.$mk.post({
        url: `${BASE_URL.BASE_URL}/MesReporting/Get/TouchScreen/v1/mes/reporting/touchScreen/search`,
        loading: "搜索中...",
        data: {
          "keyword": key,
          "ptyid": 0,
          "company_id": 1,
          "search_rules": [
          ],
          "end_time": 0,
          "company_token": process.env.VUE_APP_COMPANYTOKEN,
          "store_id": 0,
          "order_bys": [
          ],
          "limit": 0,
          "project_token": process.env.VUE_APP_APPTOKEN,
          "beid": 1,
          "page": 1,
          "start_time": 0
        },
        useBigInt: true,
      }).then(a => {
        this.loading = false
        this.tableDataStaff = a.data.mes_staff || [];
        this.tableDataProcesses = a.data.mes_processes || [];
        this.tableDataOrders = a.data.production_order_array || [];

      }).catch((a) => {
        this.loading = false
        this.$mk.error(a.data.msg);
      });
    },


    keydownEvent(e) {
      let event = e.$event;
      const input = event.target;
      let inputValue = input.value;
      this.scanEntry = input.value;
      const now = Date.now();
      if (event.key === 'Enter') {



        if (inputValue && inputValue.indexOf('{') == 0) {
          inputValue = inputValue.replace(/：/g, ":");
          inputValue = inputValue.replace(/，/g, ",");
          inputValue = inputValue.replace(/”/g, "\"");
          console.log(inputValue)
          let v = JSONbig.parse(inputValue);
          console.log(v)
          this.lastScanTime = now;
          if (v.types == 'staff') {
            this.loadStaff({ id: v.id });
          }

          if (v.types == "processes") {
            this.loadProcesses({ id: v.id });
          }

          if (v.types == "reporting") {
            this.loadReporting({ id: v.id });
          }


          setTimeout(() => {
            const $pulldown = this.$refs.pulldownRef
            if ($pulldown) {
              $pulldown.hidePanel()
            }
          }, 20);


          input.value = '';
          this.scanEntry = '';
          return;
        }

        setTimeout(() => {

          input.value = '';

          this.scanEntry = '';

        }, 10);

        return;
      }

      setTimeout(() => {


        if (this.lastScanTime) {
          // 如果上次扫码时间在200毫秒以内，则什么也不做
          if (now - this.lastScanTime < 200) {

            return;
          }
        }

        this.doLoadData();


      }, 100);

    },

    loadStaff({ id }) {
      this.loading = true
      this.$mk.get({
        url: `${BASE_URL.BASE_URL}/MesReporting/Get/TouchScreen/v1/mes/reporting/touchScreen/getIdentity/${process.env.VUE_APP_BEID}/${process.env.VUE_APP_PTYID}/${process.env.VUE_APP_COMPANY_ID}/0/${process.env.VUE_APP_APPTOKEN}/${process.env.VUE_APP_COMPANYTOKEN}/${id}`,

        useBigInt: true,
      }).then(a => {
        this.selectStaff({ data: a.data.mes_staff })
      });
    },
    loadProcesses({ id }) {
      this.loading = true
      this.$mk.get({
        url: `${BASE_URL.BASE_URL}/MesReporting/Get/TouchScreen/v1/mes/reporting/touchScreen/getProcess/${process.env.VUE_APP_BEID}/${process.env.VUE_APP_PTYID}/${process.env.VUE_APP_COMPANY_ID}/0/${process.env.VUE_APP_APPTOKEN}/${process.env.VUE_APP_COMPANYTOKEN}/${id}`,

        useBigInt: true,
      }).then(a => {
        this.formOptions3.data = a.data.mes_processes
      });
    },
    loadReporting({ id }) {
      this.loading = true
      this.$mk.get({
        url: `${BASE_URL.BASE_URL}/MesReporting/Get/TouchScreen/v1/mes/reporting/touchScreen/getVehicle/${process.env.VUE_APP_BEID}/${process.env.VUE_APP_PTYID}/${process.env.VUE_APP_COMPANY_ID}/0/${process.env.VUE_APP_APPTOKEN}/${process.env.VUE_APP_COMPANYTOKEN}/${id}`,

        useBigInt: true,
      }).then(a => {
        this.formOptions4.data = a.data.production_order_array
      });
    },

    selectStaff({ data }) {
      let data2 = Object.assign({}, data);
      if (data2.mes_processes) {
        data2.processName = data2.mes_processes.name;
      }


      this.formOptions2.data = data2
    },

    suffixClick() {
      const $pulldown = this.$refs.pulldownRef
      if ($pulldown) {
        $pulldown.togglePanel()
      }
    },
    cellClickEventProcesses({ row }) {
      let data = Object.assign({}, row);
      this.formOptions3.data = data
    },
    cellClickEventOrders({ row }) {
      console.log(row)
      const $pulldown = this.$refs.pulldownRef
      if ($pulldown) {
        $pulldown.hidePanel()
      }

      let data = Object.assign({}, row);


      this.formOptions4.data = data
    },
    cellClickEventStaff({ row }) {
      this.selectStaff({ data: row })
    },


    save() {

      let postdata = Object.assign({},this.formOptions.data);

      postdata.staff_uid = this.formOptions2.data.id;


      postdata.order_id = this.formOptions4.data.order_id;
      postdata.production_order_id = this.formOptions4.data.production_order_id;
      postdata.materials_id = this.formOptions4.data.materials_id;
      postdata.batch_id = this.formOptions4.data.id;
      postdata.batch_no = this.formOptions4.data.batch_no;
      postdata.production_plan_id = this.formOptions4.data.production_plan_id;
      postdata.production_dispatch_id = this.formOptions4.data.production_dispatch_id; 
      postdata.production_type = this.formOptions4.data.production_type;
      postdata.production_num = this.formOptions4.data.production_num;
      postdata.production_unit = this.formOptions4.data.production_unit;
      postdata.production_time = this.formOptions4.data.start_time;
      postdata.production_is_finish = this.formOptions4.data.is_finish;
      postdata.reporting_type = this.formOptions4.data.reporting_type;
      postdata.car_no = this.formOptions4.data.car_no;
      postdata.materials_code = this.formOptions4.data.materials_code;
       

      
      postdata.stage_id = this.formOptions3.data.sort_id;
      postdata.step_id = this.formOptions3.data.id;
      postdata.step_name = this.formOptions3.data.name;


      if(postdata.soil_date){
        postdata.soil_date = parseInt(new Date(postdata.soil_date).getTime() / 1000); // 转换为时间戳
      }else{
        postdata.soil_date = 0
      }
 
      postdata.loss_number = parseFloat(postdata.loss_number || 0)

      if(!postdata.staff_uid){
        this.$mk.error("请先选择员工");
        return;
      }

      if(!postdata.production_order_id){
        this.$mk.error("请先选择随车联");
        return;
      }

      if(!postdata.step_id){
        this.$mk.error("请先选择工序");
        return;
      }

      this.$mk.post({
        url: `${BASE_URL.BASE_URL}/MesReporting/Get/TouchScreen/v1/mes/reporting/touchScreen/create`,
        loading: "报工中...",
        data: {
          "ptyid": parseInt(process.env.VUE_APP_PTYID),
          "project_token":  process.env.VUE_APP_APPTOKEN ,
          "store_id": 0,
          "beid": parseInt(process.env.VUE_APP_BEID),
          "company_token": process.env.VUE_APP_COMPANYTOKEN,
          "mes_reporting_create_request": postdata,
          "company_id": parseInt(process.env.VUE_APP_COMPANY_ID)
        },
        useBigInt: true,
      }).then(a => {
        console.log(a)
        if (a.code == 200) {
          this.$mk.success("报工成功");
        } else {

          this.$mk.error(a.msg || a.message);
        }

      });
    },


  },
  // 监听属性
  watch: {

  }
};

</script>


<style>
.page-body {
  padding: 30px;
  background: #f4f4f4;
}

.formtabs .ant-tabs-tabpane {
  /* background: white; */
  padding: 12px;
}

.gridPanel {
  height: calc(100vh - 600px);
}

.footerbar {
  padding-left: 10px;
}

.imagePanel {
  cursor: pointer;
  padding: 10px;
  width: 100px;

  img {
    width: 80px;
    height: 80px;
  }
}

.oplinks2 svg {
  width: 18px;
  height: 18px;
}

.oplinks2 i {
  margin-left: 5px;
}

.search-dropdown {
  width: 1000px;
  height: 440px;
  background-color: #fafafa;
  box-shadow: 0 0 6px 2px rgba(0, 0, 0, 0.1);
  display: flex;
  flex-direction: row;
}

.search-dropdown-column {
  flex: 1;
  margin-left: 6px;
  margin-right: 6px;
  padding-top: 0;
}

.search-dropdown-column h3 {
  background: #d2d2d2;
  line-height: 30px;
  margin: 0;
  padding-left: 10px;
  color: white;
  font-size: 14px;
}

.container {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}

.card {
  background-color: white;
  margin-top: 10px;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0px 0px 3px rgba(0, 0, 0, 0.1);
}

.card h4 {
  font-weight: bold;
  font-size: 17px;
}

.left {
  flex: 6;
}

.right {
  flex: 3;
  margin-left: 10px;
}

.card .vxe-form .vxe-form--item-inner {
  min-height: 24px;
}

.card .vxe-form .vxe-form--item {
  padding: 1px;
}

.formtitle {
  font-weight: bold;
  font-size: 14px;
}
</style>
