<template>
  <div>
    <div class="page-body page-body-touch">
      <vxe-input ref="inputx" style="width:400px" v-model="searchName" placeholder="搜索工艺布产等信息"
        @keydown="keydownEvent"></vxe-input>
      <a-icon type="scan" :style="{ fontSize: '22px', color: '#08c', marginLeft: '10px' }" @click="inputFocus" />


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

          <div class="card" style="max-height: 585px;overflow-y: auto;">
            <h4>工艺布产工序</h4>

            <div v-if="detailsData && detailsData.length">
              <div v-for="item in detailsData" :key="item.id" class="card-item">
                <!--  -->

                <h3>【部件】{{ item.component_detail ? item.component_detail.name : '' }}
                  <div class="card-item-progress-img">
                    <img v-if="item.component_img" @click.stop="$hevueImgPreview(item.component_img)"
                      style="width:50px;height:50px;" :src="item.component_img" />
                    <span v-else></span>
                  </div>
                </h3>
                <div class="gx-item">

                  <div class="gx-item-col">
                    <div v-if="item.department_detail && item.department_detail.name">部门：{{ item.department_detail.name }}
                    </div>
                    <div>工序：{{ item.process_detail ? item.process_detail.name : '' }}</div>

                    <div style="font-size: 16px;font-weight: bold;">
                      状态：{{ item.is_complete ? "已完成" : (item.is_send ? "已发料" : "未发料") }}
                      <span v-if="item.complete_time">({{ getDateValueString(item.complete_time) }})</span>
                    </div>
                  </div>
                  <div class="gx-item-col">
                    <div>
                      <a-button type="primary" @click="pageSend(item)" v-if="item.is_send !== 1">发料</a-button>
                      <a-button @click="pageSend(item, true)" v-else-if="!item.is_complete">撤销发料</a-button>
                      <a-button style="margin-left: 3px;" type="primary" @click="pageReport(item)"
                        v-if="item.is_send && item.is_complete !== 1">报工</a-button>
                      <a-button style="margin-left: 3px;" @click="pageReport(item, true)"
                        v-if="item.is_complete == 1">撤销报工</a-button>
                    </div>
                    <div style="margin-top: 10px;font-size: 14px;" v-if="item.plan_complete_time">
                      计划完成:{{ getDateValueString(item.plan_complete_time) }}
                    </div>

                  </div>
                </div>



                <div class="card-item-progress">


                  <a-progress type="circle" :percent="formatProgress(item.progress)" :width="50" />
                </div>
                <!--  -->
              </div>

            </div>
            <div v-else style="min-height: 500px;">

              <div v-for="ditem in detailsData4" :key="ditem.id" class="card-item">
                <!--  -->

                <h3>【部件】{{ ditem.component_detail ? ditem.component_detail.name : '' }}
                  <div class="card-item-progress-img">
                    <img v-if="ditem.component_img" @click.stop="$hevueImgPreview(ditem.component_img)"
                      style="width:50px;height:50px;" :src="ditem.component_img" />
                    <span v-else></span>
                  </div>
                </h3>

                <div v-for="item in ditem.progressList" :key="item.id">

                  <div class="gx-item">
                    <div class="gx-item-col">

                      <div v-if="item.department_detail && item.department_detail.name">部门：{{ item.department_detail.name
                      }}</div>
                      <div>工序：{{ item.process_detail ? item.process_detail.name : '' }}</div>

                      <div style="font-size: 14px;font-weight: bold;">状态：
                        {{ item.is_complete ? "已完成" : (item.is_send ? "已发料" : "未发料") }}
                        <span v-if="item.complete_time">({{ getDateValueString(item.complete_time) }})</span>
                      </div>
                    </div>
                    <div class="gx-item-col">
                      <div>
                        <a-button type="primary" @click="pageSend(item)" v-if="item.is_send !== 1">发料</a-button>
                        <a-button @click="pageSend(item, true)" v-else-if="!item.is_complete">撤销发料</a-button>

                        <a-button style="margin-left: 3px;" type="primary" @click="pageReport(item)"
                          v-if="item.is_send && item.is_complete !== 1">报工</a-button>

                        <a-button style="margin-left: 3px;" @click="pageReport(item, true)"
                          v-if="item.is_complete == 1">撤销报工</a-button>
                      </div>
                      <div style="margin-top: 10px;font-size: 14px;" v-if="item.plan_complete_time">
                        计划完成:{{ getDateValueString(item.plan_complete_time) }}
                      </div>

                    </div>
                  </div>

                </div>



                <div class="card-item-progress">

                  <a-progress type="circle" :percent="formatProgress(ditem.progress)" :width="50" />
                </div>


                <!--  -->
              </div>


            </div>


          </div>
          <div class="card">
            <h4>部门进度汇总</h4>


            <vxe-table border show-overflow keep-source ref="xTable3" :height="230" :data="detailsData3">
              <vxe-column field="name" title="部门名称" width="150"></vxe-column>
              <vxe-column field="code" title="部门编码" width="110"></vxe-column>
              <vxe-column field="process_num" title="工序数" width="90"></vxe-column>
              <vxe-column type="expand" title="工序明细" width="160" v-if="false">
                <template #content="{ row }">
                  <a-table :columns="sub_columns" :data-source="row.progressList"
                    style="border:1px solid #afafaf;margin: 15px;">
                    <span slot="progress" slot-scope="progress">
                      <a-progress type="line" :percent="progress" />
                    </span>
                  </a-table>
                </template>
              </vxe-column>
              <vxe-column field="progress" :cellRender="{ name: 'progress' }" title="进度" width="150"></vxe-column>
            </vxe-table>


          </div>
        </div>
        <div class="right">

          <a-tabs v-model="tabKey" @change="tabChange">
            <a-tab-pane key="1" tab="布产详情">

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



            </a-tab-pane>
            <a-tab-pane key="2" tab="即将超时布产列表" force-render>
              <vxe-table border show-overflow keep-source ref="xTable3" :height="715" :row-config="{ height: 80 }"
                :data="poData" @cell-dblclick="cellDblclick1">
                <vxe-column title="操作" width="90">
                  <template #default="{ row }">
                    <a-button @click="selectPoInfo(row)">选择</a-button>
                  </template>
                </vxe-column>

                <vxe-column field="code" title="编码" width="130"></vxe-column>
                <vxe-column field="mold_master_name" title="模具师傅" width="110"></vxe-column>
                <vxe-column field="engineer_name" title="工程师傅" width="110"></vxe-column>
                <vxe-column field="complete_time" formatter="formatDate" title="预计完成时间" width="160"></vxe-column>
                <vxe-column title="图片" width="75">
                  <template #default="{ row }">
                    <img v-if="row.mold_detail.image" style="width:52px;height:52px;" :src="row.mold_detail.image"
                      @click.stop="$hevueImgPreview(row.mold_detail.image)" />
                    <span v-else></span>
                  </template>
                </vxe-column>
                <vxe-column field="mold_detail" formatter="formatRef" :params="{ dataType: 'object', textField: 'name' }"
                  title="模具" width="400"></vxe-column>
                <vxe-column field="remark" title="备注" width="160"></vxe-column>
              </vxe-table>



            </a-tab-pane>

            <a-tab-pane key="3" tab="部门工序列表" force-render>

              <!-- 部门筛选 选中时触发loadDataProgress -->
              <a-space>
                <a-select @select="DepartmentChange" :value="department_list_options_default" style="width: 200px"
                  :options="department_list_options"></a-select>
              </a-space>
              <!-- 发料筛选 -->
              <a-select @select="IsSendChange" :value="IsSendDefault" style="width: 200px"
                :options="IsSendOptions"></a-select>
              <!-- 完工筛选 -->
              <a-select @select="IsCompleteChange" :value="IsCompleteDefault" style="width: 200px"
                :options="IsCompleteOptions"></a-select>
              <a-select @select="IsMasterChange" :value="IsMasterDefault" style="width: 200px"
                :options="IsMasterOptions"></a-select>
                <a-select @select="IsEngineerChange" :value="IsEngineerDefault" style="width: 200px"
                :options="IsEngineerOptions"></a-select>
              <vxe-table border show-overflow keep-source ref="xTable3" :height="715" :row-config="{ height: 80 }"
                :data="detailDataProgress" @cell-dblclick="cellDblclick">
                <vxe-column title="操作" width="90">
                  <template #default="{ row }">
                    <a-button @click="selectPoProgressInfo(row)">选择</a-button>
                  </template>
                </vxe-column>

                <vxe-column field="process_name" title="工序名称" align="center" width="110"></vxe-column>
                <vxe-column title="图片" width="75">
                  <template #default="{ row }">
                    <img v-if="row.component_img" style="width:52px;height:52px;" :src="row.component_img"
                      @click.stop="$hevueImgPreview(row.component_img)" />
                    <span v-else></span>
                  </template>
                </vxe-column>
                <vxe-column field="component_name" title="部件名称" width="110"></vxe-column>
                <!-- <vxe-column field="production_id" title="布产单id" width="210"></vxe-column> -->
                <vxe-column field="production_code" title="布产单号" width="110"></vxe-column>
                <vxe-column field="mold_master_name" align="center" title="模具师傅" width="110"></vxe-column>
                <vxe-column field="engineer_name" align="center" title="工程师傅" width="110"></vxe-column>
                <vxe-column field="plan_complete_time" align="center" formatter="formatDate" title="预计完成时间"
                  width="160"></vxe-column>
                <vxe-column field="status" title="状态" align="center" width="100"></vxe-column>
                <!-- <vxe-column field="is_send" title="发料" width="160"></vxe-column> -->
                <vxe-column field="send_time" align="center" formatter="formatDate" title="发料日期" width="140"></vxe-column>
                <vxe-column field="reality_complete_time" formatter="formatDate" title="完工日期" width="160"></vxe-column>
                <vxe-column field="remark" title="备注" width="160"></vxe-column>
              </vxe-table>



            </a-tab-pane>
          </a-tabs>

          <div style="margin:10px 0;">

            <div data-show="true" class="ant-alert ant-alert-info ant-alert-with-description"
              style="padding: 5px 5px 5px 20px;border:none;">
              <span class="ant-alert-message">操作性提示</span>
              <span class="ant-alert-description" style="line-height:18px;">
                <p>
                  1，先选择布产单，可以输入编码(输入后回车) （也可以扫码 ）
                </p>
                <p>
                  2，输入1#部门编码 搜索，当前布产单的部门相关工序 （也可以扫码 ）
                </p>
                <p>
                  3，输入2#工序编码 搜索，当前布产单的相关工序（追加） （也可以扫码 ）
                </p>
              </span>

            </div>

          </div>



        </div>
      </div>


    </div>
    <vxe-modal v-model="showRowEditDialog" width="600" :position="{top:'20%'}" title="添加布产备注" show-footer>
      <template #default>
        <p style="font-size: 20px;font-weight: bold;">布产单号:{{ nowRow.code }}</p>
        <a-textarea v-model="nowRow.remark" :rows="4" style="font-size: 20px;"/>
      </template>
      <template #footer>
        <a-button @click="saveRowRemark">确认</a-button>
      </template>
    </vxe-modal>
    <vxe-modal v-model="showProcessEditDialog" width="600" :position="{top:'20%'}" title="添加工序备注" show-footer>
      <template #default>
        <p style="font-size: 20px;font-weight: bold;">布产单号:{{ nowProcessRow.production_code }}</p>
        <p style="font-size: 20px;font-weight: bold;">工序:{{ nowProcessRow.process_detail.name }}</p>
        <a-textarea v-model="nowProcessRow.remark" :rows="4" style="font-size: 20px;"/>
      </template>
      <template #footer>
        <a-button @click="saveRemark">确认</a-button>
      </template>
    </vxe-modal>



  </div>
</template>

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

import XEUtils from 'xe-utils'  // 加载xe-utils 
import JSONbig from 'json-bigint'

export default {

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

  },

  data() {





    var pageData = {

      actions: {
      },
      sub_columns: [

        {
          title: '工序名',
          dataIndex: 'process_detail_name',
          key: 'process_detail_name',
        },
        {
          title: '工序编号',
          dataIndex: 'process_detail_code',
          key: 'process_detail_code',
        },
        {
          title: '部件名',
          dataIndex: 'component_detail_name',
          key: 'component_detail_name',
        },

        {
          title: '进度',
          dataIndex: 'progress',
          key: 'progress',
          slots: { title: 'progress' },
          scopedSlots: { customRender: 'progress' },
        },
      ],
      tabKey: '2',
      keyName: 'id',
      // 是否编辑模式
      isEdit: false,
      showProcessEditDialog:false,
      showRowEditDialog:false,
      nowRow: {},
      nowProcessRow: {},
      currentId: 0,
      detailsData: [],  // 工序详情列表
      detailsData3: [],  // 部门列表


      detailsData4: [], //按部件分组  

      detailDataProgress: [],  // 工序部门列表


      processesDepartmentId: 0, // 按部门id筛选
      department_list: [], // 部门列表
      // department_list_options 默认值为全部
      department_list_options_default: "0",
      department_list_options: [
        {
          label: "全部部门",
          value: "0",
        }
      ],  // 部门列表下拉框

      processesIsComplete: "0", // 按是否完成筛选
      IsCompleteDefault: "0",
      IsCompleteOptions: [
        {
          label: "未完成",
          value: "0",
        },
        {
          label: "已完成",
          value: "1",
        }
      ],  // 是否完成下拉框
      user_list: [], // 员工列表
      IsMasterDefault: "0",
      IsMasterOptions: [
        {
          label: "全部模具师傅",
          value: "0",
        }
      ],
      IsEngineerDefault: "0",
      IsEngineerOptions: [
        {
          label: "全部工程师傅",
          value: "0",
        }
      ],
      processesIsSend: "1", // 按是否已发料筛选
      IsSendDefault: "1",
      IsSendOptions: [
        {
          label: "未发料",
          value: "0",
        },
        {
          label: "已发料",
          value: "1",
        }
      ],  // 是否完成下拉框

      poData: [],
      tips: ["点一", "点二", "点三"],
      current_mold_production_order_component_processes: [],
      current_mold_production_order_component: [],
      formOptions2: {
        data: {
        },
        // 标题宽度
        titleWidth: 130,
        // 标题对齐方式
        titleAlign: 'right',
        // 表单校验规则
        rules: {
        },
        // 表单项
        items: [


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

          { field: 'manufacture_cycle', dataRule: { type: 'timestamp' }, title: '制作周期', span: 24, itemRender: { name: 'MkFormInputShow', props: { params: { dataType: 'date' } } } },
          { field: 'remark', title: '备注', span: 24, itemRender: { name: 'MkFormInputShow', props: { params: { isTextarea: true } } } },
          {
            field: 'progress', title: '进度', span: 24, itemRender: {
              name: 'MkFormProgress', props: {
                params: {
                  type: "circle"
                }
              }
            }
          },




        ]
      },


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

                {
                  title: '模具师傅', span: 24,
                  field: 'mold_master_user_detail',
                  itemRender: {
                    name: 'MkFormInputShow', props: {
                      params: {
                        dataType: "object",
                        valueField: "id",
                        textField: "name"
                      }
                    }
                  }
                },
                {
                  title: '工程师傅', span: 24,
                  field: 'engineer_name',
                  itemRender: {
                    name: 'MkFormInputShow', props: {
                    }
                  }
                },
              ]
            },
            {
              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: []

    };


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

    return pageData;
  },

  computed: {

  },


  created() {

    setTimeout(() => {
      this.$refs.inputx.focus(); // 获取焦点

      this.loadPoData();
      this.loadDataProgress(185208273404694528, 0);
      this.loadDeaprtmentData();
    }, 200)

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

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

    tabChange() {
      if (this.tabKey == '2') {
        this.loadPoData();
      }
      if (this.tabKey == '3') {
        this.loadDataProgress(0, 0);
        this.loadDeaprtmentData();
        this.loadUserData();
      }
    },
    loadPoData() {
      this.$mk.post({
        url: `${BASE_URL.BASE_URL}/MoldProductionOrder/Get/TouchScreen/v1/mold/production/order/touchScreen/order/list`,
        loading: "搜索中...",
        data: {
          "beid": parseInt(process.env.VUE_APP_BEID),
          "ptyid": 0,
          "company_id": parseInt(process.env.VUE_APP_COMPANY_ID),
          "store_id": 0,
          "project_token": process.env.VUE_APP_APPTOKEN,
          "company_token": process.env.VUE_APP_COMPANYTOKEN,
          "search_rules": [
          ],
          "end_time": 0,
          "order_bys": [{ "column": "complete_time", "order": "asc" }],
          "limit": 0,
          "page": 1,
          "start_time": 0
        },
        useBigInt: true,
      }).then(a => {
        this.poData = JSON.parse(JSON.stringify(a.data.MoldProductionOrder));
        console.log(this.poData)
      });
    },

    loadDeaprtmentData() {
      this.$mk.post({
        url: `${BASE_URL.BASE_URL}/BaseDepartment/Get/v1/base/department/anonymous/list`,
        loading: "加载中...",
        data: {
          "beid": parseInt(process.env.VUE_APP_BEID),
          "ptyid": 0,
          "company_id": parseInt(process.env.VUE_APP_COMPANY_ID),
          "store_id": 0,
          "project_token": process.env.VUE_APP_APPTOKEN,
          "company_token": process.env.VUE_APP_COMPANYTOKEN,
          "search_rules": [
          ],
          "end_time": 0,
          "order_bys": [],
          "limit": 100,
          "page": 1,
          "start_time": 0
        },
        useBigInt: true,
      }).then(a => {
        this.department_list = JSON.parse(JSON.stringify(a.data.BaseDepartment));
        // 将department_list 中的name值赋值给department_list_options
        this.department_list_options = this.department_list.map(item => {
          return {
            value: item.id,
            label: item.name
          }
        })
        // 将department_list_options 前面加上全部
        this.department_list_options.unshift({
          label: "全部部门",
          value: "0",
        })

      });
    },
    loadUserData(){
      this.$mk.post({
        url: `${BASE_URL.BASE_URL}/MesStaff/v1/mes/staff/list`,
        loading: "加载中...",
        data: {
          "beid": parseInt(process.env.VUE_APP_BEID),
          "ptyid": 0,
          "company_id": parseInt(process.env.VUE_APP_COMPANY_ID),
          "store_id": 0,
          "project_token": process.env.VUE_APP_APPTOKEN,
          "company_token": process.env.VUE_APP_COMPANYTOKEN,
          "search_rules": [
          ],
          "end_time": 0,
          "order_bys": [],
          "limit": 100,
          "page": 1,
          "start_time": 0
        },
        useBigInt: true,
      }).then(a => {
        this.user_list = a.data.MesStaff;
        // 将department_list 中的name值赋值给department_list_options
        this.IsMasterOptions = this.user_list.map(item => {
          console.log(item.id)
          return {
            value: item.id,
            label: item.name
          }
        })
        this.IsEngineerOptions = this.user_list.map(item => {
          return {
            value: item.id,
            label: item.name
          }
        })
        // 将department_list_options 前面加上全部
        this.IsMasterOptions.unshift({
          label: "全部模具师傅",
          value: 0,
        })
        this.IsEngineerOptions.unshift({
          label: "全部工程师傅",
          value: 0,
        })
      });
    },
    selectPoInfo(row) {
      this.loadProductionOrder({ id: row.id })
    },

    selectPoProgressInfo(row) {
      this.loadProductionOrder({ id: row.production_id })
    },

    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 || []));
        if (this.tableDataOrders.length) {
          this.loadProductionOrder({ id: this.tableDataOrders[0].id });
        }
      }).catch((a) => {
        this.loading = false
        this.$mk.error(a.data.msg);
      });
    },


    loadDataProgress() {

      // 定义 search_rules 
      let search_rules = [
      ]
      if (this.processesDepartmentId > 0) {
        // 有部门id search_rules 条件加上 department_id
        search_rules.push({
          "column": "department_id",
          "mode": "=",
          "value": this.processesDepartmentId
        })
      }
      if (this.processesIsComplete > 0) {
        // 没有部门id search_rules 条件加上 is_complete 默认为0
        search_rules.push({
          "column": "is_complete",
          "mode": "=",
          "value": this.processesIsComplete
        })
      } else {
        search_rules.push({
          "column": "is_complete",
          "mode": "=",
          "value": "0",
        })
      }
      if (this.processesIsSend > 0) {
        // 没有部门id search_rules 条件加上 is_complete 默认为0
        search_rules.push({
          "column": "is_send",
          "mode": "=",
          "value": this.processesIsSend
        })
      } else {
        search_rules.push({
          "column": "is_send",
          "mode": "=",
          "value": "0"
        })
      }
      // if (this.processesIsMaster > 0) {
      //   search_rules.push({
      //     "column": "mold_master_uid",
      //     "mode": "=",
      //     "value": this.processesIsMaster
      //   })
      // } 
      // if (this.processesIsEngineer > 0) {
      //   search_rules.push({
      //     "column": "engineer_uid",
      //     "mode": "=",
      //     "value": this.processesIsEngineer
      //   })
      // } 
      this.loading = true
      this.$mk.post({
        url: `${BASE_URL.BASE_URL}/MoldProductionOrder/Get/TouchScreen/v1/mold/production/order/touchScreen/processes/list`,
        loading: "查询中...",
        data: {
          "beid": parseInt(process.env.VUE_APP_BEID),
          "ptyid": 0,
          "company_id": parseInt(process.env.VUE_APP_COMPANY_ID),
          "store_id": 0,
          "project_token": process.env.VUE_APP_APPTOKEN,
          "company_token": process.env.VUE_APP_COMPANYTOKEN,
          "search_rules": search_rules,
          "order_bys": [
            { "column": "plan_complete_time", "order": "asc" }
          ],
          "page": 1,
          "limit": 200,
          "start_time": 0,
          "end_time": 0,
          mold_master_uid:this.processesIsMaster,
          engineer_uid:this.processesIsEngineer,
        },
        useBigInt: true,
      }).then(a => {
        this.loading = false
        this.detailDataProgress = JSON.parse(JSON.stringify(a.data.mold_production_order_touch_screen_processes || []));

        this.detailDataProgress.forEach(item => {

          item.department_name = item.department_detail.name
          item.production_code = item.production_detail.code
          item.process_name = item.process_detail.name
          item.component_name = item.component_detail.name;
        })

        // this.detailDataProgress 中将  production_code 等于 "" 的数据删除
        this.detailDataProgress = this.detailDataProgress.filter(item => item.production_code != "")
      }).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.substr(inputValue.indexOf('{'));
        }

        if (inputValue && inputValue.indexOf('{') == -1 && inputValue.indexOf('2#') == 0) {
          this.loadProcesses({ code: inputValue.substr(2) })
        }
        else if (inputValue && inputValue.indexOf('{') == -1 && inputValue.indexOf('1#') == 0) {
          this.loadDepartment({ code: inputValue.substr(2) })
        }
        else if (inputValue && inputValue.indexOf('{') == -1) {
          this.loadData({ key: inputValue })
        }

        else 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 == "department") {
            this.loadDepartment({ id: v.id });
          }
          if (v.types == "mold_production_order") {
            this.loadProductionOrder({ id: v.id });
          }
          if (v.types == "mold_production_order_component_processes") {
            this.loadVehicle({ id: v.id });
          }

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


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

        setTimeout(() => {

          input.value = '';

          this.searchName = '';
          this.scanEntry = '';

        }, 10);

        return;
      }

    },

    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, code }) {
      let ds = this.detailsData || [];

      if (id) {

        if (ds.filter(a => a.process_id.toString() == id.toString()).length) {
          return;
        }

        this.current_mold_production_order_component_processes.forEach(item => {

          if (item.process_id.toString() == id.toString()) {
            ds.push(item);
          }
        })
        this.detailsData = ds;

      }
      else if (code) {

        if (ds.filter(item => item.process_detail && item.process_detail.code == code).length) {
          return;
        }

        this.current_mold_production_order_component_processes.forEach(item => {

          if (item.process_detail && item.process_detail.code == code) {
            ds.push(item);
          }
        })
        this.detailsData = ds;

      }

    },
    getDateValueString(v) {
      if (!v) return '';
      return XEUtils.toDateString(new Date(v * 1000), 'yyyy-MM-dd');
    },

    resetProcesses() {
      let ds = JSON.parse(JSON.stringify(this.detailsData || []))
      let newDs = [];
      this.current_mold_production_order_component_processes.forEach(item => {
        ds.forEach(o => {
          if (item.id.toString() == o.id.toString()) {
            newDs.push(item);
          }
        })
      })
      this.detailsData = newDs;

    },

    loadDepartment({ id, code }) { // 加载部门
      let ds = [];

      if (id) {

        if (ds.filter(a => a.department_id.toString() == id.toString()).length) {
          return;
        }

        this.current_mold_production_order_component_processes.forEach(item => {

          if (item.department_id.toString() == id.toString()) {
            ds.push(item);

          }
          this.current_mold_production_order_component.forEach(item1 => {
            if (item.component_line == item1.component_line) {
              item.component_img = item1.component_img;
            }
          })
        })


        this.detailsData = ds;

      }





      else if (code) {
        this.current_mold_production_order_component_processes.forEach(item => { // 循环所有的
          // 如果当前的部门编码等于输入的部门编码
          if (item.department_detail && item.department_detail.code == code) {
            ds.push(item);
          }
          this.current_mold_production_order_component.forEach(item1 => {
            if (item.component_line == item1.component_line) {
              item.component_img = item1.component_img;
            }
          })
        })
        this.detailsData = ds;

      }

    },


    loadProductionOrder({ id, resetProcesses }) {

      this.currentId = id;
      this.tabKey = '1';

      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);


        let mold_production_order_component_processes = JSON.parse(JSON.stringify(row.mold_production_order_component_processes));
        let ds3 = JSON.parse(JSON.stringify(row.department_progress || []));

        let ds4 = JSON.parse(JSON.stringify(row.mold_production_order_component || []));
        this.current_mold_production_order_component = JSON.parse(JSON.stringify(row.mold_production_order_component || []));

        ds3.forEach(item => {
          item.progressList = [];
          mold_production_order_component_processes.forEach(pitem => {
            if (pitem.department_id == item.id) {
              pitem.process_detail_name = pitem.process_detail.name
              pitem.process_detail_code = pitem.process_detail.code
              pitem.component_detail_name = pitem.component_detail.name

              item.progressList.push(pitem);
            }
          })
        })


        ds4.forEach(item => {
          item.progressList = [];
          mold_production_order_component_processes.forEach(pitem => {
            if (pitem.component_line == item.component_line) {
              pitem.process_detail_name = pitem.process_detail.name
              pitem.process_detail_code = pitem.process_detail.code
              pitem.component_detail_name = pitem.component_detail.name

              item.progressList.push(pitem);
            }
          })
        })

        this.detailsData3 = ds3;

        this.detailsData4 = ds4;


        data3.mold_master_user_detail = row.mold_master_user_detail;
        data3.engineer_name = row.engineer_name;
        this.formOptions2.data = data2
        this.formOptions3.data = data3
        this.current_mold_production_order_component_processes = row.mold_production_order_component_processes;

        if (resetProcesses === true) {
          this.resetProcesses();
        } else {

          this.detailsData = [];
        }


      });
    },

    loadVehicle({ id }) {

      this.loading = true
      this.$mk.get({
        url: `${BASE_URL.BASE_URL}/MoldProductionOrder/Get/TouchScreen/v1/mold/production/order/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}`,
      }).then(a => {

        let row = a.data.mold_production_order_component_processes;
        this.loadProductionOrder({ id: row.production_id });

      });
    },


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


      this.formOptions2.data = data2
    },

    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()
      }

      this.loadProductionOrder({ id: row.id });


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


    pageReport(item, isUndo) {

      this.$mk.confirm(!isUndo ? '您确定要报工吗？' : '您确定撤销吗？').then(type => {
        if (type == 'confirm') {

          this.$mk.post({
            url:
              isUndo ?
                `${BASE_URL.BASE_URL}/MoldProductionOrder/Get/TouchScreen/v1/mold/production/order/touchScreen/cancel` :
                `${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("操作成功");

              this.loadProductionOrder({ id: this.currentId, resetProcesses: true });

            } else {

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

          });

        }
      });


    },
    pageSend(item, isUndo) {

      console.log(item)

      this.$mk.confirm(!isUndo ? '您确定要发料吗？' : '您确定撤销吗？').then(type => {
        if (type == 'confirm') {
          this.$mk.post({
            url: isUndo ?
              `${BASE_URL.BASE_URL}/MoldProductionOrder/Get/TouchScreen/v1/mold/production/order/touchScreen/cancelSendMaterial` :
              `${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("操作成功");

              this.loadProductionOrder({ id: this.currentId, resetProcesses: true });

            } else {

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

          });
        }
      });


    },
    // 将进度百分比取小数点后两位
    formatProgress(progress) {
      // 判断如果大于5个字符串，就截取前6个字符串
      if (progress.length > 5) {
        progress = progress.substring(0, 6);
        // 将百分比转换为小数点后两位
        progress = parseFloat(progress).toFixed(2);
      }
      return progress;

    },
    DepartmentChange(e) {
      this.processesDepartmentId = e
      this.department_list_options_default = e
      this.loadDataProgress()
    },
    IsCompleteChange(e) {
      this.processesIsComplete = e
      this.IsCompleteDefault = e
      this.loadDataProgress()
    },
    IsSendChange(e) {
      this.processesIsSend = e
      this.IsSendDefault = e
      this.loadDataProgress()
    },
    IsMasterChange(e){
      this.processesIsMaster = e
      this.IsMasterDefault = e
      this.loadDataProgress()
      console.log(e)
    },
    IsEngineerChange(e){
      this.processesIsEngineer = e
      this.IsEngineerDefault = e
      this.loadDataProgress()
      console.log(e)
    },
    cellDblclick({ row, column }){
      console.log(row,column)
      this.nowProcessRow = Object.assign({}, row);
      this.showProcessEditDialog = true;
    },
    cellDblclick1({ row, column }){
      console.log(row,column)
      this.nowRow = Object.assign({}, row);
      this.showRowEditDialog = true;
    },
    saveRemark(){
     
      this.$mk.post({
        url: `${BASE_URL.BASE_URL}/MoldProductionOrder/Get/TouchScreen/v1/mold/production/order/touchScreen/saveProcessRemark`,
        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(this.nowProcessRow.id),
          "company_id": parseInt(process.env.VUE_APP_COMPANY_ID),
          "remark": this.nowProcessRow.remark
        },
        useBigInt: true,
      }).then(a => {
        console.log(a)
        if (a.code == 200) {
          this.$mk.success("操作成功");
          this.loadProductionOrder({ id: this.currentId, resetProcesses: true });
          this.showProcessEditDialog = false;

        }else{
          this.showProcessEditDialog = false;
        }
      })

    },
    saveRowRemark(){
     
     this.$mk.post({
       url: `${BASE_URL.BASE_URL}/MoldProductionOrder/Get/TouchScreen/v1/mold/production/order/touchScreen/saveRemark`,
       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(this.nowRow.id),
         "company_id": parseInt(process.env.VUE_APP_COMPANY_ID),
         "remark": this.nowRow.remark
       },
       useBigInt: true,
     }).then(a => {
       console.log(a)
       if (a.code == 200) {
         this.$mk.success("操作成功");
         this.loadProductionOrder({ id: this.currentId, resetProcesses: true });
         this.showRowEditDialog = false;

       }else{
         this.showRowEditDialog = false;
       }
     })

   }


  },
  // 监听属性
  watch: {

  }
};

</script>


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

.page-body-touch {
  font-size: 22px;
}

.page-body-touch .vxe-form {
  font-size: 22px;
}

.page-body-touch .vxe-table--render-default {
  font-size: 22px;
}


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

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

.footerbar {
  padding-left: 10px;
}

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


}

.imagePanel 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: grid;
  grid-template-columns: 550px 1fr;
  grid-gap: 0px;

}

.left {}

.right {
  margin-left: 10px;
  overflow-x: scroll;
}



.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: 22px;
}


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

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

.formtitle {
  font-weight: bold;
  font-size: 22px;
}

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

.gx-item-col {
  flex: 5;
}

.card-item {
  position: relative;
  padding-top: 5px;
}

.card-item-progress {

  position: absolute;
  right: 5px;
  top: 15px;
}

.card-item h3 {
  position: relative;
  padding-bottom: 10px;
  margin: 0;
  height: 60px;
  line-height: 60px;
}

.card-item-progress-img {

  position: absolute;
  right: 65px;
  top: 10px;
  line-height: 0px;
}

.bottom-toast {
  background-color: #5CB85C;
  width: 100%;
  padding: 10px;
  box-sizing: border-box;
  text-align: center;
  font-size: 15px;
  color: #333;
}
</style>