<template>
  <div v-if="visible" class="right-page">
    <!-- 内容区 -->
    <div class="page-body">
      <ele-pro-table
        height="calc(80vh - 160px)"
        ref="fileTable"
        :columns="jobColumns1"
        :datasource="workList"
        v-show="rightMode == 'list'"
      >
        <template v-slot:action="{ row }">
          <el-link type="primary" @click="fileDetails(row)">详情</el-link>
        </template>
      </ele-pro-table>

      <fileBrowse
        ref="browseRef"
        v-if="rightMode == 'detail'"
        @close="closeDetail"
      />
    </div>

    <pickingList
      isType="pick"
      ref="pickingListRef"
      @allSelection="allSelection"
    />
  </div>
</template>

<script>
  import pickingList from './pickingList.vue';
  import fileBrowse from './newFileBrowse.vue';
  import {
    workorderList,
    getCode,
    craftFiles,
    filePageAPI,
    fileReleaseAPI
  } from '@/api/produce/workOrder';
  import { typeName } from '../common.js';
  import { batchSave } from '@/api/produce/picking';

  export default {
    components: {
      pickingList,
      fileBrowse
    },
    props: {
      workListIds: {
        type: Array,
        default() {
          return [];
        }
      },
      taskId: {
        type: String,
        default() {
          return null;
        }
      }
    },
    data() {
      return {
        visible: false,
        workList: [],
        rules: {},

        pickCode: null,
        pickName: null,
        jobColumns1: [
          {
            label: '编码',
            prop: 'code',
            width: 180,
            align: 'center',
            showOverflowTooltip: true
          },

          {
            prop: 'name',
            label: '文档名称',
            align: 'center',
            slot: 'name',
            showOverflowTooltip: true,
            minWidth: 200
          },

          {
            prop: 'storagePath',
            label: '文件名称',
            align: 'center',

            showOverflowTooltip: true,
            minWidth: 200,
            formatter: (_row, _column, cellValue) => {
              return cellValue[0]?.name;
            }
          },

          {
            prop: 'version',
            label: '版本',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 100
          },

          {
            prop: 'createTime',
            label: '创建时间',
            showOverflowTooltip: true,
            align: 'center',
            minWidth: 110
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 260,
            align: 'center',
            resizable: false,
            slot: 'action',
            showOverflowTooltip: true
          }
        ],

        typeName,

        tableRules: {},
        rightMode: 'list',
        currentRow: null,
        itemData: null,
        type: 1
      };
    },
    computed: {
      taskObj() {
        return this.$store.state.user.taskObj;
      }
    },

    watch: {},
    methods: {
      // datasource({ page, where, limit }) {

      //     let req = {
      //         "taskId": this.taskId,
      //         "workOrderId": this.workListIds[0]
      //     }

      //     return craftFiles({
      //         ...req,
      //         pageNum: page,
      //         size: limit,
      //     });
      // },

      open(req) {
        this.itemData = req;
        this.type = 1;
        this.workList = [];
        craftFiles(req).then((res) => {
          let _ids = [];
          if (res.length != 0) {
            res.forEach((e) => {
              _ids.push(e.id);
            });
            const ids = _ids.join(',');
            this.getFilepProcess(ids);
          }
        });

        this.visible = true;
      },

      openTwo(req) {
        this.itemData = req;
        this.type = 2;
        this.workList = [];
        fileReleaseAPI({
          fileType: 0,
          isQueryAll: 1,
          jobNumber: '',
          lcyStatus: '3',
          loginName: '',
          name: req.productCode,
          pageNum: 1,
          size: 10
        }).then((res) => {
          this.workList = res.list;
        });

        this.visible = true;
      },

      async getFilepProcess(ids) {
        await filePageAPI({
          ids: "'" + ids + "'"
        }).then((res) => {
          this.workList = res;
        });
      },

      fileDetails(row) {
        this.currentRow = row;
        this.rightMode = 'detail';

        this.$nextTick(() => {
          this.$refs.browseRef.setFileUrl(row);
        });
      },

      closeDetail() {
        this.rightMode = 'list';
        if (this.type == 1) {
          this.open(this.itemData);
        } else if (this.type == 2) {
          this.openTwo(this.itemData);
        }
      },

      async getOrderCode() {
        this.pickCode = await getCode('pick_order_code');
      },

      removeItem(idx, index) {
        this.workList[idx].pickList.splice(index, 1);
      },

      handleClose() {
        this.visible = false;
        this.$emit('close', false);
      },

      getList() {
        console.log(123);
      },

      openPicking(id, item) {
        this.$refs.pickingListRef.open(id, item);
      },

      allSelection(id, list) {
        this.workList.forEach((e) => {
          if (e.id == id) {
            e.pickList = list;
            this.$forceUpdate();
          }
        });
      },

      save() {
        console.log(this.workList);
        if (this.workList.length > 0) {
          let bol;
          let _i;
          bol = this.workList.every((e, i) => {
            _i = i;
            return (
              Object.prototype.hasOwnProperty.call(e, 'pickList') &&
              e.pickList.length > 0
            );
          });

          if (!bol) {
            this.$message.warning(
              `生成工单${this.workList[_i].code}领料不能为空`
            );
            return false;
          }
        }

        if (this.workList.length > 0) {
          let name;
          let bol2;
          let _i;

          this.workList.forEach((e, i) => {
            _i = i;
            console.log(e.pickList);
            bol2 = e.pickList.every((y) => {
              name = y.name;
              return (
                Object.prototype.hasOwnProperty.call(y, 'demandQuantity') &&
                Number(y.demandQuantity) > 0
              );
            });
          });

          if (!bol2) {
            this.$message.warning(
              `${this.workList[_i].code}的${name}数量不能为空`
            );
            return false;
          }
        }

        let _arr = [];
        _arr = this.workList.map((m) => {
          m.instanceList = [];
          m.bomDetailDTOSList = [];
          m.pickList.forEach((e) => {
            if (
              Object.prototype.hasOwnProperty.call(e, 'isBom') &&
              e.isBom == 1
            ) {
              m.bomDetailDTOSList.push(e);
            } else {
              m.instanceList.push(e);
            }
          });

          m.workOrderId = m.id;
          delete m.id;

          return {
            ...m
          };
        });

        let param = {
          allPickList: _arr,
          pickName: this.pickName,
          pickCode: this.pickCode
        };

        batchSave(param).then((res) => {
          this.$message.success('领料成功');
          this.$emit('close', true);
        });
      }
    },

    created() {
      this.getList();
    }
  };
</script>

<style lang="scss" scoped>
  .table_content {
    margin-bottom: 10px;
  }

  .tableZ_box {
    border: 1px solid #e3e5e5;
    margin: 6px 0;

    &:last-child {
      border-bottom: none;
    }

    .row {
      width: 100%;
      display: flex;
    }

    .col {
      width: calc(100% / 5);
      display: flex;
      align-items: center;
      min-width: 200px;
      min-height: 32px;
      border-bottom: 1px solid #e3e5e5;
      border-right: 1px solid #e3e5e5;

      &:last-child {
        border-right: none;
      }

      .name {
        display: flex;
        align-items: center;
        padding: 4px;
        width: 80px;
        height: 100%;
        background-color: #d0e4d5;
        color: #000;
      }

      .content {
        padding: 4px 6px;
        color: #000;
      }
    }

    .pd6 {
      padding: 0 6px;
    }
  }

  .right-page {
    height: 100%;
    display: flex;
    flex-direction: column;
    min-height: 0;
  }

  .page-body {
    flex: 1;
    min-height: 0;
    overflow: hidden;
  }

  .page-body .pro-table {
    height: 100%;
  }

  .page-footer {
    flex-shrink: 0;
    padding: 10px 0;
    border-top: 1px solid #ebeef5;
    text-align: right;
    background: #fff;
  }
</style>

<style>
  :v-deep .el-form-item__error {
    bottom: -6px !important;
  }
</style>
