<template>
  <div>


    <vxe-table border show-overflow keep-source ref="xTable" :data="detailsData" @pulldownSelected="onPulldownSelected"
               @popupSelected="onPopupSelected" :export-config="{}" @edit-closed="afterEditEvent"
               @edit-actived="beforeEditEvent"
               :edit-config="{ trigger: 'click', mode: 'cell', icon: 'vxe-icon-edit', showStatus: false, beforeEditMethod: beforeEditMethod }">
      <vxe-column title="图片" width="120" align="center">
        <template #default="{ row }">
          <div v-if="row.component_img" style="position: relative;" class="imgbox">
            <img style="width:50px;height:50px;" :src="row.component_img"
                 @click.stop="$hevueImgPreview(row.component_img)"/>
            <div class="imgicons" style="position:absolute;right:0px;top:0px;">
              <div>
                <a @click="imgDel({ row })">
                  <a-icon type="close-circle"/>
                </a>
              </div>
              <div>
                <a-upload name="file" accept="image/*" :before-upload="beforeUpload" :show-upload-list="false">
                  <a @click="uploadClick({ row })">
                    <a-icon type="edit"/>
                  </a>
                </a-upload>
              </div>
            </div>
          </div>

          <span v-else>
            <a-upload name="file" accept="image/*" :before-upload="beforeUpload" :show-upload-list="false">
              <a-button type="link" @click="uploadClick({ row })">上传图片</a-button>
            </a-upload>

          </span>

        </template>
      </vxe-column>

      <vxe-column field="component_num" title="数量" width="70" align="center"
                  :edit-render="{ name: '$input', props: { type: 'number' } }"></vxe-column>
      <vxe-column field="production_type" title="布产类型" width="100" align="center" :edit-render="{}">
        <template #default="{ row }">
          <span>{{ $mk.formatEnum(row.production_type, options_production_type) }}</span>
        </template>
        <template #edit="{ row }">
          <vxe-select v-model="row.production_type" transfer>
            <vxe-option v-for="item in options_production_type" :key="item.value" :value="item.value"
                        :label="item.label"></vxe-option>
          </vxe-select>
        </template>
      </vxe-column>

      <vxe-column v-if="false" field="process_detail" title="加工人员" width="160" :params="editor_d1_process"
                  formatter="formatRef" :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>


      <vxe-column field="prepare_process_time" title="预备加工日期" width="130" formatter="formatDate" align="center"
                  :edit-render="{ name: '$input', props: { type: 'date' } }"></vxe-column>
      <vxe-column field="plan_complete_time" title="计划完成日期" width="130" formatter="formatDate" align="center"
                  :edit-render="{ name: '$input', props: { type: 'date' } }"></vxe-column>


      <vxe-column title="完成" width="100" align="center" v-if="getDataId()">
        <template #default="{ row }">
          <div v-if="row.id">
            <div v-if="row.complete_time">
              <a-tooltip placement="topLeft" :title="'完成时间：'+$mk.getDateString(row.complete_time)"
                         arrow-point-at-center>
                {{ $mk.getDate(row.complete_time) }}
              </a-tooltip>
            </div>
            <a-button v-else :disabled="!(isComponentOutProduct() || pageIsComplete())" @click.stop="pageComplete(row)"
                      type="primary">完成
            </a-button>
          </div>
        </template>
      </vxe-column>


      <!-- <vxe-column field="complete_type" v-if="getDataId() && isDetails1Complete()" title="完工人员类型" width="160"
        :params="{ data: options_user_type }" formatter='formatEnum'></vxe-column> -->


      <vxe-column field="spec" title="规格" align="center" width="140"
                  :edit-render="{ name: '$input', props: {} }"></vxe-column>
      <vxe-column field="surface" title="表面工艺" align="center" width="140"
                  :edit-render="{ name: '$input', props: {} }"></vxe-column>
      <vxe-column field="inlay" title="镶件材料" align="center" width="140"
                  :edit-render="{ name: '$input', props: {} }"></vxe-column>

      <vxe-column field="processing_cost" title="成本价" align="center" width="auto"
                  :edit-render="{ name: '$input', props: {type: 'number' } }"></vxe-column>
      <vxe-column field="remark" title="备注" align="center" width="auto"
                  :edit-render="{ name: '$input', props: {} }"></vxe-column>


    </vxe-table>

    <vxe-table v-if="!isComponentOutProduct()" border show-overflow keep-source ref="xTable2" :data="detailsData2"
               @pulldownSelected="onPulldownSelected" @popupSelected="onPopupSelected" :export-config="{}"
               @edit-closed="afterEditEvent" @edit-actived="beforeEditEvent"
               :edit-config="{ trigger: 'click', mode: 'cell', icon: 'vxe-icon-edit', showStatus: false, beforeEditMethod: beforeEditMethod }">
      <vxe-column width="60" v-if="!readonly">
        <template #default="{ row }">
          <div class="oplinks2">
            <a @click.stop="pageAdd2(row)" title="新增">
              <a-icon class="icon" type="plus-circle"/>
            </a>
            <a @click.stop="pageDelete2(row)" title="删除">
              <a-icon class="icon" type="delete"/>
            </a>
          </div>
        </template>
      </vxe-column>
      <vxe-column field="process_detail" title="工序" width="130" :params="editor_processes" formatter="formatRef"
                  :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>
      <vxe-column field="department_detail" title="部门" width="120" :params="editor_department" formatter="formatRef"
                  :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>
      <vxe-column field="progress" title="进度" width="120" :cellRender="{ name: 'progress' }"></vxe-column>


      <vxe-column v-if="false" field="process_uid_detail" title="加工人员" width="160" :params="editor_process_uid"
                  formatter="formatRef" :edit-render="{ name: 'MkGridDataSelector' }"></vxe-column>

      <vxe-column field="progress" v-if="isEdit" :cellRender="{ name: 'progress' }" title="进度"
                  width="100"></vxe-column>

      <vxe-column field="prepare_process_time" title="预备加工日期" width="130" formatter="formatDate" align="center"
                  :edit-render="{ name: '$input', props: { type: 'date' } }"></vxe-column>
      <vxe-column field="plan_complete_time" title="计划完成日期" width="130" formatter="formatDate" align="center"
                  :edit-render="{ name: '$input', props: { type: 'date' } }"></vxe-column>


      <vxe-column title="发料" width="100" align="center" v-if="getDataId()">
        <template #default="{ row }">
          <div v-if="row.id">
            <a-button v-if="!row.is_send" @click.stop="pageSend(row)" type="primary">发料</a-button>
            <div v-if="row.is_send">

              <a-tooltip placement="topLeft" :title="'发料时间：'+$mk.getDateString(row.send_time)"
                         arrow-point-at-center>
                <a-button v-if="!isComponentDone() && !row.is_complete" @click.stop="pageSend(row, true)">撤销
                </a-button>
              </a-tooltip>
            </div>
          </div>
        </template>
      </vxe-column>

      <vxe-column title="完成" width="100" align="center" v-if="getDataId()">
        <template #default="{ row }">
          <div v-if="row.id && row.is_send">
            <a-tooltip placement="topLeft" :title="'发料时间：'+$mk.getDateString(row.send_time)" arrow-point-at-center>
              <a-button v-if="!row.is_complete" @click.stop="pageDone(row)" type="primary">完成</a-button>
            </a-tooltip>
            <div v-if="row.is_complete">
              <a-tooltip placement="topLeft"
                         arrow-point-at-center>
                <template #title>
                  {{ row.send_time ? '发料时间：' + $mk.getDateString(row.send_time) : '' }}
                  <br/>
                  {{ row.complete_time ? '完成时间：' + $mk.getDateString(row.complete_time) : '' }}
                </template>
                <a-button v-if="!isComponentDone()" @click.stop="pageDone(row, true)">撤销</a-button>
              </a-tooltip>
            </div>
          </div>
        </template>
      </vxe-column>

      <vxe-column field="send_type" v-if="getDataId() && readonly" title="发料人员" width="80" align="center"
                  :params="{ data: options_user_type }" formatter='formatEnum'></vxe-column>


      <vxe-column field="complete_type" v-if="getDataId() && readonly" title="完工人员" width="80" align="center"
                  :params="{ data: options_user_type }" formatter='formatEnum'></vxe-column>

      <vxe-column field="processing_cost" title="加工成本(元)" width="130"
                  :edit-render="{ name: '$input', props: {type: 'number' } }"></vxe-column>
      <vxe-column field="remark" title="备注" width="auto" :edit-render="{ name: '$input', props: {} }"></vxe-column>


    </vxe-table>


  </div>
</template>

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

import XEUtils from 'xe-utils' // 加载xe-utils
const settings = require('../basic/settings.js');

export default {

  name: '',
  components: {},
  props: {
    pageMode: {
      type: String,
      default: "edit"
    },
    readonly: {
      type: Boolean,
      default: false
    },
    itemData: {
      type: Object
    },
    dataId: {}

  },

  data() {

    const options_production_type = settings.options_production_type;
    const options_is_complete = settings.options_is_complete;
    const options_is_send = settings.options_is_send;
    const options_user_type = settings.options_user_type;

    //let _this = this;
    // 页面数据变量
    var pageData = {

      options_production_type: options_production_type,
      options_is_complete: options_is_complete,
      options_is_send: options_is_send,
      options_user_type: options_user_type,
      // 当前项目名称
      currentConfigName: "",
      // 当前项目ID
      currentBeid: 0,

      pageStatus: '',

      uploadDefaultImg: null,
      detailDataFieldName: "mold_production_order",

      actions: {
        get: `${BASE_URL.BASE_URL}/MoldProductionOrder/v1/mold/production/order/detail`,
        create: `${BASE_URL.BASE_URL}/MoldProductionOrder/v1/mold/production/order/create`,
        update: `${BASE_URL.BASE_URL}/MoldProductionOrder/v1/mold/production/order/update`
      },

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

      // 新增模式表单项
      addModeItems: [],


      detailsSourceData: [],
      detailsData: [],
      deletedDetailsData: [],

      detailsData2: [],
      deletedDetailsData2: [],
      editor_component: {
        dataType: "object",
        valueField: "id",
        textField: "name",
        listdataFieldName: 'MoldComponent',
        mapper: [
          {fromField: "id", field: "component_id"}
        ],
        dataUrl: `${BASE_URL.BASE_URL}/MoldComponent/v1/mold/component/list`
      },
      editor_department: {
        dataType: "object",
        valueField: "id",
        textField: "name",
        listdataFieldName: 'BaseDepartment',
        mapper: [
          {fromField: "id", field: "department_id"}
        ],
        dataUrl: `${BASE_URL.BASE_URL}/BaseDepartment/v1/base/department/list`
      },

      editor_processes: {
        dataType: "object",
        valueField: "id",
        textField: "name",
        listdataFieldName: 'MesProcesses',
        mapper: [
          {fromField: "id", field: "process_id"}
        ],
        dataUrl: `${BASE_URL.BASE_URL}/MesProcesses/v1/mes/processes/list`
      },

      editor_d1_process: {
        dataType: "object",
        valueField: "id",
        textField: "name",
        listdataFieldName: 'MesStaff',
        mapper: [
          {fromField: "id", field: "process_uid"}
        ],
        dataUrl: `${BASE_URL.BASE_URL}/MesStaff/v1/mes/staff/list`
      },
      editor_d1_send: {
        dataType: "object",
        valueField: "id",
        textField: "name",
        listdataFieldName: 'MesStaff',
        mapper: [
          {fromField: "id", field: "send_uid"}
        ],
        dataUrl: `${BASE_URL.BASE_URL}/MesStaff/v1/mes/staff/list`
      },
      editor_process_uid: {
        dataType: "object",
        valueField: "id",
        textField: "name",
        listdataFieldName: 'MesStaff',
        mapper: [
          {fromField: "id", field: "process_uid"}
        ],
        dataUrl: `${BASE_URL.BASE_URL}/MesStaff/v1/mes/staff/list`
      },

      currentRow: null

    };


    return pageData;
  },

  computed: {
    desc() {
      return this.$t('editPageDesc')
    }
  },


  created() {

    this.pageInit();

  },
  // 函数
  methods: {

    pageInit() {


      this.itemData.mold_production_order_component.forEach(item => {
        if (!item.production_type) {
          item.production_type = 1;
        }
      })


      this.detailsData = JSON.parse(JSON.stringify(this.itemData.mold_production_order_component || []));
      this.detailsData2 = JSON.parse(JSON.stringify(this.itemData.mold_production_order_component_processes || []));


      //this.loadDepartment();

      this.detailsDataInit();

      this.postDataUpdate();

    },

    isComponentDone() {
      for (let i = 0; i < this.detailsData.length; i++) {
        if (!this.detailsData[i].is_complete) {
          return false;
        }
      }
      return true;
    },

    isComponentOutProduct() {
      for (let i = 0; i < this.detailsData.length; i++) {
        if (this.detailsData[i].production_type == 2) {
          return true;
        }
      }
      return false;
    },

    loadDepartment() {

      for (let i = 0; i < this.detailsData2.length; i++) {
        if (this.detailsData2[i].process_id && !this.detailsData2[i].department_id) {

          this.$mk.post({
            url: `${BASE_URL.BASE_URL}/MesProcesses/v1/mes/processes/detail`,
            data: {
              id: this.$mk.toBigInt(this.detailsData2[i].process_id)
            },
            useBigInt: true,
          }).then(a => {
            if (a.code == 200) {
              let row = a.data.mes_processes;
              if (row.department_id) {
                this.detailsData2[i].department_id = row.department_id;
                this.detailsData2[i].department_detail = row.department_detail;


              }
            }
          });


        }
      }
      setTimeout(() => {
        this.detailsData2 = JSON.parse(JSON.stringify(this.detailsData2));
      }, 500);
    },

    isDetails1Complete() {
      for (let i = 0; i < this.detailsData.length; i++) {
        if (this.detailsData[i].is_complete) {
          return true;
        }
      }
      return false;
    },


    pageIsComplete() {
      for (let i = 0; i < this.detailsData.length; i++) {
        if (this.detailsData[i].is_complete) {
          return false;
        }
      }
      for (let i = 0; i < this.detailsData2.length; i++) {
        if (!this.detailsData2[i].is_complete) {
          return false;
        }
      }
      return true;
    },


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

    detailsDataInit() {
      for (let i = this.detailsData && this.detailsData.length; i < 1; i++) {
        this.detailsData.push({});
      }
      for (let i = this.detailsData2 && this.detailsData2.length; i < 1; i++) {
        this.detailsData2.push({});
      }
    },
    // 获取路由的id参数
    getDataId() {
      let dataId = this.dataId;
      return dataId;
    },
    getDataId_BigInt() {
      let dataId = this.getDataId();
      return this.$mk.toBigInt(dataId);
    },
    pageComplete(row) {

      this.$mk.confirm('您确定完成吗？').then(type => {
        if (type == 'confirm') {
          this.$mk.post({
            url: `${BASE_URL.BASE_URL}/MoldProductionOrder/v1/mold/production/order/component/reporting`,
            data: {
              id: this.$mk.toBigInt(row.id)
            },
            useBigInt: true,
          }).then(a => {
            if (a.code == 200) {
              this.$mk.success("操作成功");
              this.$emit("reloadData");
            }
          });
        }
      });


    },

    pageDone(row, isUndo) {


      this.$mk.confirm(!isUndo ? '您确定要报工吗？' : '您确定撤销吗？').then(type => {
        if (type == 'confirm') {
          this.$mk.post({
            url: isUndo ?
                `${BASE_URL.BASE_URL}/MoldProductionOrder/v1/mold/production/order/component/processes/CancelReporting` :
                `${BASE_URL.BASE_URL}/MoldProductionOrder/v1/mold/production/order/component/processes/Reporting`,
            data: {
              id: this.$mk.toBigInt(row.id)
            },
            useBigInt: true,
          }).then(a => {
            if (a.code == 200) {
              this.$mk.success("操作成功");
              this.$emit("reloadData");
            }
          });
        }
      });


    },

    pageSend(row, isUndo) {

      this.$mk.confirm(!isUndo ? '您确定要发料吗？' : '您确定撤销吗？').then(type => {
        if (type == 'confirm') {
          this.$mk.post({
            url: isUndo ?
                `${BASE_URL.BASE_URL}/MoldProductionOrder/v1/mold/production/order/component/processes/CancelSendMaterial` :
                `${BASE_URL.BASE_URL}/MoldProductionOrder/v1/mold/production/order/component/processes/SendMaterial`,
            data: {
              id: this.$mk.toBigInt(row.id)
            },
            useBigInt: true,
          }).then(a => {
            if (a.code == 200) {
              this.$mk.success("操作成功");
              this.$emit("reloadData");
            }
          });
        }
      });


    },

    pageAdd(row) {
      const $table = this.$refs.xTable
      const record = {}
      if (row) {
        this.detailsData = JSON.parse(JSON.stringify(this.detailsData))
        this.detailsData.splice($table.getRowSeq(row), 0, record);
      } else {
        this.detailsData.push(record)
      }
    },
    pageDelete(row) {

      if (this.detailsData.length == 1) {
        this.$mk.success("至少保留一行");
        return;
      }
      const $table = this.$refs.xTable;
      if (row.id) {
        this.deletedDetailsData.push(this.$mk.toBigInt(row.id))
      }
      this.detailsData.splice($table.getRowSeq(row) - 1, 1);

      this.postDataUpdate();
    },

    pageAdd2(row) {
      const $table = this.$refs.xTable2
      const record = {
        component_line: this.detailsData[0].component_line,
        component_id: this.detailsData[0].component_id
      }
      if (row) {
        this.detailsData2 = JSON.parse(JSON.stringify(this.detailsData2))
        this.detailsData2.splice($table.getRowSeq(row), 0, record);
      } else {
        this.detailsData2.push(record)
      }

    },
    pageDelete2(row) {
      if (this.detailsData2.length == 1) {
        this.$mk.success("至少保留一行");
        return;
      }
      const $table = this.$refs.xTable2;
      if (row.id) {
        this.deletedDetailsData2.push(this.$mk.toBigInt(row.id))
      }
      this.detailsData2.splice($table.getRowSeq(row) - 1, 1);

      this.postDataUpdate();
    },

    postDataUpdate() {
      let postdata = {};

      this.detailsData2.forEach(item => {
        item.component_line = this.detailsData[0].component_line;
      })

      postdata.mold_production_order_component = this.$mk.getPostFieldValue({
        rowFilter: (row) => {
          return row.id || row.component_id
        },
        dataId: this.getDataId_BigInt(),
        list: this.detailsData,
        deletedList: this.deletedDetailsData,
        fieldName: 'production_id',
        dataRule: [
          {field: 'production_type', type: 'integer'},
          {field: 'component_num', type: 'integer'},
          {field: 'prepare_process_time', type: 'timestamp'},
          {field: 'plan_complete_time', type: 'timestamp'},

          {field: 'order_id', type: 'bigint'},
          {field: 'id', type: 'bigint'},
          {field: 'update_uid', type: 'bigint'},
          {field: 'complete_uid', type: 'bigint'},
          {field: 'create_uid', type: 'bigint'},
          {field: 'mold_id', type: 'bigint'},
          {field: 'component_id', type: 'bigint'},
          {field: 'process_uid', type: 'bigint'},
          {field: 'send_uid', type: 'bigint'},
          {field: 'process_id', type: 'bigint'},
          {field: 'purchase_cost', type: 'bigint'},
          {field: 'processing_cost', type: 'bigint'},
        ]
      });

      if (this.isComponentOutProduct()) {

        postdata.mold_production_order_component_processes = this.getDataId() ? {
          insertList: [],
          updateList: [],
          deleteList: []
        } : [];
      } else {

        let list = [...this.detailsData2];
        list.forEach(item => {
          item.component_id = this.detailsData[0].component_id;
        })
        postdata.mold_production_order_component_processes = this.$mk.getPostFieldValue({
          rowFilter: (row) => {
            return row.id || (row.component_id && row.process_id)
          },
          dataId: this.getDataId_BigInt(),
          list: list,
          deletedList: this.deletedDetailsData2,
          fieldName: 'production_id',
          dataRule: [

            {field: 'id', type: 'bigint'},
            {field: 'prepare_process_time', type: 'timestamp'},
            {field: 'plan_complete_time', type: 'timestamp'},


            {field: 'order_id', type: 'bigint'},
            {field: 'send_uid', type: 'bigint'},
            {field: 'complete_uid', type: 'bigint'},
            {field: 'update_uid', type: 'bigint'},
            {field: 'create_uid', type: 'bigint'},
            {field: 'component_id', type: 'bigint'},
            {field: 'department_id', type: 'bigint'},
            {field: 'process_id', type: 'bigint'},
            {field: 'process_uid', type: 'bigint'},
            {field: 'purchase_cost', type: 'bigint'},
            {field: 'processing_cost', type: 'bigint'},
          ]
        });
      }


      this.itemData.postdata = postdata;
    },

    beforeEditMethod({column, row}) {
      if (this.readonly) {
        return false;
      }
      console.log(column, row);
      return true;
    },
    afterEditEvent({column, row}) {
      console.log(column, row);

      this.postDataUpdate();


    },
    beforeEditEvent({column, row}) {
      console.log(column, row);
      if (this.readonly) {
        return false;
      }
    },
    onPulldownSelected({row, selectedData, column}) {
      console.log(selectedData);


      if (column.field == 'process_detail' && column.title == '工序') {
        row.department_detail = selectedData.department_detail || {};
        row.department_id = selectedData.department_id;
      }
    },
    onPopupSelected({rows, name, params}) {
      console.log(rows, name, params);
    },


    beforeUpload(file) {

      var suffix = file.name.substring(file.name.lastIndexOf(".") + 1);
      this.$mk.uploadFile(file, suffix, (url) => {
        this.currentRow.component_img = url;
        this.$forceUpdate();
        if (this.currentRow.id) {
          this.$mk.post({
            url: `${BASE_URL.BASE_URL}/MoldProductionOrder/v1/mold/production/order/upload`,
            data: {id: this.currentRow.id, image: url},
            useBigInt: true
          }).then(a => {
            console.log(a);
          });
        }
      });

      return false
    },

    imgDel({row}) {

      row.component_img = "";
      this.$mk.post({
        url: `${BASE_URL.BASE_URL}/MoldProductionOrder/v1/mold/production/order/upload`,
        data: {id: row.id, image: ""},
        useBigInt: true
      }).then(a => {
        console.log(a);
      });
    },


    uploadClick({row}) {
      this.currentRow = row;
    }

  },
  // 监听属性
  watch: {}
};

</script>


<style scoped lang="less">
.page-body {
  padding: 30px;
  background: @base-bg-color;
}

.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;
}

.imgicons {
  display: none;;
}

.imgbox:hover .imgicons {
  display: block;
}
</style>
