<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>
      </template>
    </vxe-pulldown>

    <div class="container">
      <div class="left">

        <div class="card">
          <h4>工艺布产工序</h4>


          <div v-for="item in detailsData" :key="item.id">
            <div class="gx-item">
              <div class="gx-item-col">

                <div>部件：{{ item.component_detail ? item.component_detail.name : '' }}</div>
                <div>工序：{{ item.process_detail ? item.process_detail.name : '' }}</div>
                
                <div>状态：{{ item.is_complete ? "已完成" : (item.is_send ? "已发料" :"未发料") }}</div>
              </div>
              <div class="gx-item-col">
                <a-button type="primary" @click="pageSend(item)" v-if="item.is_send !== 1">发料</a-button>

                <a-button type="primary" @click="pageReport(item)" v-if="item.is_send && item.is_complete !== 1">报工</a-button>
              </div>
            </div>
          </div>


        </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>


  </div>
</template>

<script>
import BASE_URL from '@/services/mes/api.js';

import JSONbig from 'json-bigint'
export default {

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

  },

  data() {





    var pageData = {

      actions: {
      },

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

      detailsData: [],

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


        { field: 'code', title: '编号', span: 8, itemRender: { name: 'MkFormInputShow' } },
        {
            title: '订单号', span: 8,
            field: 'mold_order', 
            itemRender: {
              name: 'MkFormInputShow', props: {
                params: {
                  dataType: "object",
                  valueField: "id",
                  textField: "code" 
                }
              }
            }
          }, 

          { field: 'manufacture_cycle', dataRule: { type: 'timestamp' }, title: '制作周期', span: 8, itemRender: { name: 'MkFormInputShow', props: { params:{dataType : 'date' }  } }},
          { field: 'draw_start_time', dataRule: { type: 'timestamp' }, title: '预计开始画图时间', span: 8, itemRender: { name: 'MkFormInputShow', props: { params:{dataType : 'date' } } } },
          { field: 'split_design_time', dataRule: { type: 'timestamp' }, title: '分模设计时间预计', span: 8, itemRender: { name: 'MkFormInputShow', props: { params:{dataType : 'date' } } } },
          { field: 'draw_time', dataRule: { type: 'timestamp' }, title: '出图时间预计', span: 8, itemRender: { name: 'MkFormInputShow', props: { params:{dataType : 'date' }} } },
          { field: 'split_design_time', dataRule: { type: 'timestamp' }, title: '分模设计时间预计', span: 8, itemRender: { name: 'MkFormInputShow', props: { params:{dataType : 'date' }} } },
          { field: 'draw_time', dataRule: { type: 'timestamp' }, title: '出图时间预计', span: 8, itemRender: { name: 'MkFormInputShow', props: { params:{dataType : 'date' } } } },
          { field: 'draw2D_time', dataRule: { type: 'timestamp' }, title: '出2D时间预计', span: 8, itemRender: { name: 'MkFormInputShow', props: {params:{dataType : 'date' } } } },
          { field: 'draw3D_time', dataRule: { type: 'timestamp' }, title: '出3D时间预计', span: 8, itemRender: { name: 'MkFormInputShow', props: { params:{dataType : 'date' } } } },
          { field: 'horizontal_frame_time', dataRule: { type: 'timestamp' }, title: '出2D时间预计', span: 8, itemRender: { name: 'MkFormInputShow', props: { params:{dataType : 'date' } } } },
          { field: 'inlay_deep_hole_time', dataRule: { type: 'timestamp' }, title: '镶件深孔钻到厂日期预计', span: 8, itemRender: { name: 'MkFormInputShow', props: { params:{dataType : 'date' } } } },
          { field: 'problem', title: '出现问题及建议反馈', span: 24, itemRender: { name: 'MkFormInputShow', props: {} } },
 
        




        ]
      },


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

              ]
            },
            {
              span: 6,
              children: [
                {
                  field: 'image', span: 24, itemRender: {
                    name: 'MkFormCropper', props: {
                      isReadonly: true
                    }
                  }
                },
              ]
            }
          ]
      },


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

          { 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: {} } },




          { 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: 'code', title: '单号' },
        { field: 'mold_name', title: '模具名' },
        { field: 'mold_code', title: '模具编号' },
      ],
      tableColumn: [
        { field: 'name', title: '名称' },

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

    };


    // 合并表单数据及配置
    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}/MoldProductionOrder/Get/TouchScreen/v1/mold/production/order/touchScreen/search`,
        loading: "搜索中...",
        data: {
          "keyword": key,
          "ptyid": 0,
          "company_id": parseInt(process.env.VUE_APP_COMPANY_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": parseInt(process.env.VUE_APP_BEID),
          "page": 1,
          "start_time": 0
        },
        useBigInt: true,
      }).then(a => {
        this.loading = false
        this.tableDataOrders =JSON.parse(JSON.stringify( a.data.mold_production_order || []));

        this.allDetailsData = JSON.parse(JSON.stringify(a.data.mold_production_order_component_processes || []));
      }).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 == "mold_production_order") {
            this.loadProductionOrder({ 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
      });
    },
    loadProductionOrder({ id }) {
      this.loading = true
      this.$mk.get({
        url: `${BASE_URL.BASE_URL}/MoldProductionOrder/Get/TouchScreen/v1/mold/production/order/touchScreen/getMoldProductionOrder/${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 => { 

        let row = a.data.mold_production_order;
        let data2 = Object.assign({}, row);
      let data3 = Object.assign({}, row.mold_detail);


      this.formOptions2.data = data2
      this.formOptions3.data = data3 
      this.detailsData = row.mold_production_order_component_processes;

      });
    },

    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 data2 = Object.assign({}, row);
      let data3 = Object.assign({}, row.mold_detail);


      this.formOptions2.data = data2
      this.formOptions3.data = data3

      let ds = [];
      this.allDetailsData.forEach(item => { 
        if ((item.production_id + '') == (row.id + '')) {
          ds.push(item);
        }
      })
      console.log(ds)
      this.detailsData = ds;
    },
    cellClickEventStaff({ row }) {
      this.selectStaff({ data: row })
    },


    pageReport(item) {


      this.$mk.post({
        url: `${BASE_URL.BASE_URL}/MoldProductionOrder/Get/TouchScreen/v1/mold/production/order/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,
          "id": this.$mk.toBigInt(item.id),
          "company_id": parseInt(process.env.VUE_APP_COMPANY_ID)
        },
        useBigInt: true,
      }).then(a => {
        console.log(a)
        if (a.code == 200) {
          this.$mk.success("报工成功");
          item.is_complete = 1;

        } else {

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

      });
    },
    pageSend(item) {

      console.log(item)
      this.$mk.post({
        url: `${BASE_URL.BASE_URL}/MoldProductionOrder/Get/TouchScreen/v1/mold/production/order/touchScreen/sendMaterial`,
        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,
          "id": this.$mk.toBigInt(item.id),
          "company_id": parseInt(process.env.VUE_APP_COMPANY_ID)
        },
        useBigInt: true,
      }).then(a => {
        console.log(a)
        if (a.code == 200) {
          this.$mk.success("发料成功");
          item.is_send = 1;

        } 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: 4;
}

.right {
  flex: 6;
  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;
}

.gx-item {
  display: flex;
  margin-top: 10px;
  border-bottom: 1px dashed #d3d3d3;
}

.gx-item-col {
  flex: 5;
}
</style>
