<template>
  <div class="transRequirementClass">
    <!-- 头部代码块查询等 -->
    <div class="top">
      <dil-form
        :formId="searchFormId"
        v-model="form1"
        @clearChange="clearChange"
        :statusIcon="false"
        labelPosition="right"
        @defaultValueGet="defaultValueGet"
      ></dil-form>
    </div>
    <div class="elDivider">
      <el-divider></el-divider>
    </div>
    <div class="buttonModel">
      <div class="operation">
        <el-button
          size="mini"
          type="primary"
          @click="btnclick(0)"
          v-privilege="activeMenu + 'ADD'"
        >
          <i class="el-icon-plus"></i>新增
        </el-button>
        <el-button size="mini" type="primary" @click="batchSubmit">
          申报
        </el-button>
        <el-button
          size="mini"
          type="danger"
          @click="logicDelete()"
          :disabled="deleteButton === 0 ? true : false"
          v-privilege="activeMenu + 'DELETE'"
        >
          删除
        </el-button>
        <el-button size="mini" type="primary" @click="exportData()"
          ><i class="el-icon-download"></i>导出(Excel)</el-button
        >
        <el-button
          size="mini"
          type="primary"
          icon="el-icon-edit-outline"
          @click="logicbulu()"
          :disabled="buluButton === 0 ? true : false"
        >
          补录（仅计次信息）
        </el-button>

        <el-button size="mini" type="primary" class="btn" @click="preview()">
          查阅应急操作手册
        </el-button>
      </div>
      <el-dialog
        title="文件预览"
        :visible.sync="dialogVisible3"
        destroy-on-close
        width="90%"
        top="10vh"
      >
        <iframe
          :src="previewUrl"
          width="100%"
          :height="singleTableHeight"
        ></iframe>
      </el-dialog>
      <div class="search">
        <el-button
          size="mini"
          type="primary"
          class="btn"
          @click="onclick(1)"
          v-privilege="activeMenu + 'QUERY'"
        >
          <i class="el-icon-search"></i>查询
        </el-button>
        <el-button
          size="mini"
          type="primary"
          class="btn"
          @click="onclickFixed"
          v-privilege="activeMenu + 'QUERYFIXED'"
        >
          <i class="el-icon-search"></i>查询固定需求
        </el-button>
        <el-button
          size="mini"
          type="primary"
          class="btn"
          @click="option.showFilter = !option.showFilter"
        >
          {{ option.showFilter ? '关闭表格过滤' : '开启表格过滤' }}
        </el-button>
      </div>
    </div>
    <el-dialog
      :title="'实际转运吨位录入'"
      :visible.sync="buludialogVisible"
      width="90%"
      :show-close="!loading"
      :close-on-click-modal="false"
    >
      <el-input
        v-model="alternateFields6"
        placeholder="请输入实际转运吨位"
      ></el-input>
      <el-button size="mini" type="primary" class="btn" @click="buluClick()">
        <i class="el-icon-search"></i>确定
      </el-button>
    </el-dialog>
    <el-dialog
      :title="
        '运输需求 - ' + (dialog.editorBox.type === 'ADD' ? '新增' : '修改')
      "
      :visible.sync="dialogVisible"
      width="90%"
      @close="clearAll"
      :show-close="!loading"
      :close-on-click-modal="false"
    >
      <el-drawer
        title="选择运单"
        :visible.sync="drawerLn2"
        direction="rtl"
        size="45%"
        :modal-append-to-body="false"
      >
        <div>
          <el-input
            v-model="inputLn"
            placeholder="请输入物资名称"
            clearable
            style="width: 200px"
          ></el-input>
          <el-button
            size="mini"
            type="primary"
            class="btn"
            @click="onclickLnSearchClick()"
          >
            <i class="el-icon-search"></i>查询
          </el-button>
        </div>
        <dilTable
          v-bind.sync="optionSearchClick"
          @radio-change="selectionChangeLn2"
        ></dilTable>
        <el-button
          size="mini"
          type="primary"
          class="btn"
          @click="handClickSearchClick()"
        >
          <i class="el-icon-search"></i>确定
        </el-button>
      </el-drawer>
      <el-tabs v-model="dialog.editorBox.activeName" type="border-card">
        <dil-form
          :formId="addFormId"
          :statusIcon="false"
          labelPosition="right"
          v-model="form2"
          @searchClick="searchClick"
          ref="form2"
          v-if="dialogVisible"
          labelWidth="120px"
          @selectChange="selectChangeForm2"
        >
        </dil-form>
      </el-tabs>
      <div class="insertClass">
        <el-button size="mini" type="primary" @click="addRow">
          <i class="el-icon-plus"></i>新增
        </el-button>
        <el-button size="mini" type="primary" @click="clearAll">
          <i class="el-icon-refresh"></i>清空
        </el-button>
      </div>
      <div class="table">
        <el-table
          :data="tableData"
          style="width: 100%; min-height: 200px !important"
          border
        >
          <el-table-column
            v-for="(item, index) in capacityType === '吊车'
              ? tableColumnList2
              : tableColumnList"
            :label="item.label"
            :prop="item.prop"
            :key="index"
            :type="item.type"
            align="center"
            :column-key="item.key"
            :width="item.width"
          >
            <template slot-scope="scope">
              <el-form :model="scope.row" ref="tableForm_1" label-width="120px">
                <template v-if="item.slotType === 'auto'">
                  <el-form-item
                    label-width="0"
                    v-if="item.isValidate"
                    :prop="item.prop"
                    :rules="[
                      { required: true, message: '请输入' + item.label + '' }
                    ]"
                  >
                    <el-autocomplete
                      clearable
                      :index="scope.$index"
                      :ref="item.prop"
                      v-autocomplete-scroll="handleScroll"
                      style="width: 100%"
                      class="inline-input"
                      v-model="scope.row[item.prop]"
                      :fetch-suggestions="
                        (queryString, cb) => {
                          querySearchTable(
                            queryString,
                            cb,
                            scope.row,
                            item.prop
                          )
                        }
                      "
                      :placeholder="`请输入${item.label}`"
                      @select="
                        handleSelectTable(
                          $event,
                          scope.row,
                          item.prop,
                          scope.$index
                        )
                      "
                      @blur="onBlur"
                    >
                      <template slot-scope="{ item }">
                        <div class="name">
                          {{ item[item.prop] }}
                          <br />
                          <span
                            v-if="item.lineName"
                            style="color: #8492a6; font-size: 13px"
                          >
                            {{ item.lineDesk }}
                          </span>
                        </div>
                      </template>
                    </el-autocomplete>
                  </el-form-item>
                  <el-form-item
                    label-width="0"
                    v-if="!item.isValidate"
                    :prop="item.prop"
                  >
                    <el-autocomplete
                      class="inline-input"
                      style="width: 100%"
                      v-model="scope.row[item.prop]"
                      :fetch-suggestions="
                        (queryString, cb) => {
                          querySearchTable(
                            queryString,
                            cb,
                            scope.row,
                            item.prop
                          )
                        }
                      "
                      :placeholder="`请输入${item.label}`"
                      @select="handleSelectTable($event, scope.row, item.prop)"
                      @blur="onBlur"
                    >
                      <template slot-scope="{ item }">
                        <div class="name">{{ item[item.prop] }}</div>
                      </template>
                    </el-autocomplete>
                  </el-form-item>
                </template>
                <template v-else-if="item.slotType === 'input'">
                  <el-form-item
                    label-width="0"
                    v-model="scope.row[item.prop]"
                    v-if="item.isValidate"
                    :prop="item.prop"
                    :rules="[
                      { required: true, message: '请输入' + item.label + '' }
                    ]"
                  >
                    <el-input
                      @focus="getInputFocus($event)"
                      v-model="scope.row[item.prop]"
                      :placeholder="`请输入${item.label}`"
                      :type="item.inputType"
                      clearable
                    >
                    </el-input>
                  </el-form-item>
                  <el-form-item
                    label-width="0"
                    v-model="scope.row[item.prop]"
                    v-if="!item.isValidate"
                    :prop="item.prop"
                  >
                    <el-input
                      @focus="getInputFocus($event)"
                      v-model="scope.row[item.prop]"
                      :placeholder="`请输入${item.label}`"
                      :type="item.inputType"
                      clearable
                    >
                    </el-input>
                  </el-form-item>
                </template>
                <template v-else-if="item.slotType === 'select'">
                  <el-form-item
                    label-width="0"
                    v-if="item.isValidate"
                    :prop="item.prop"
                    :rules="[
                      { required: true, message: '请选择' + item.label + '' }
                    ]"
                  >
                    <el-select
                      clearable
                      v-model="scope.row[item.prop]"
                      :placeholder="`请选择${item.label}`"
                    >
                      <el-option
                        v-for="(e, index) in item.options"
                        :key="index"
                        :label="e.label"
                        :value="e.value"
                      ></el-option>
                    </el-select>
                  </el-form-item>
                  <el-select
                    clearable
                    v-if="!item.isValidate"
                    v-model="scope.row[item.prop]"
                    :placeholder="`请选择${item.label}`"
                  >
                    <el-option
                      v-for="(e, index) in item.options"
                      :key="index"
                      :label="e.label"
                      :value="e.value"
                    ></el-option>
                  </el-select>
                </template>
                <template v-else-if="item.slotType === 'dateTime'">
                  <el-date-picker
                    v-model="scope.row[item.prop]"
                    :type="item.dateType"
                    placeholder="选择日期时间"
                    clearable
                    value-format="timestamp"
                  >
                  </el-date-picker>
                </template>
                <template v-else-if="item.slotType === 'button'">
                  <el-button
                    size="mini"
                    type="danger"
                    @click="deleteRow(scope.$index, scope.row)"
                    v-privilege="activeMenu + 'DELETE'"
                  >
                    删除
                  </el-button>
                  <el-button
                    size="mini"
                    type="primary"
                    @click="copyRow(scope.$index, scope.row)"
                    v-privilege="activeMenu + 'DELETE'"
                  >
                    复制
                  </el-button>
                </template>
                <template v-else>
                  <span>{{ scope.row[item.prop] }}</span>
                </template>
              </el-form>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <el-drawer
        title="选择匹配需求代码"
        :visible.sync="drawerLn"
        direction="rtl"
        size="45%"
        :modal-append-to-body="false"
      >
        <div>
          <el-button
            size="mini"
            type="primary"
            class="btn"
            @click="onclickLn()"
          >
            <i class="el-icon-search"></i>查询
          </el-button>
        </div>
        <dilTable
          v-bind.sync="optionLn"
          @radio-change="selectionChangeLnCode"
        ></dilTable>
        <el-button size="mini" type="primary" class="btn" @click="handClick()">
          <i class="el-icon-search"></i>确定
        </el-button>
      </el-drawer>

      <span slot="footer" class="dialog-footer">
        <el-button size="mini" type="success" @click="showLineDrawer()">
          快捷规则查询
        </el-button>
        <el-button size="mini" @click="dialogVisible = false">取 消</el-button>
        <el-button
          size="mini"
          type="primary"
          @click="submitBut()"
          :disabled="buttonType === 0 ? true : false"
          >确 定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog
      :title="'运输需求 -  操作'"
      :visible.sync="dialogVisible2"
      width="90%"
      :show-close="!loading"
      :close-on-click-modal="false"
    >
      <el-tabs v-model="dialog.editorBox.activeName2" type="border-card">
        <dil-form
          :formId="574"
          :statusIcon="false"
          labelPosition="right"
          v-model="form4"
          ref="form4"
          v-if="dialogVisible2"
          labelWidth="120px"
        >
        </dil-form>
      </el-tabs>
      <div class="table">
        <el-table
          :data="tableData"
          style="width: 100%; min-height: 200px !important"
          border
        >
          <el-table-column
            v-for="item in tableColumnList"
            :label="item.label"
            :prop="item.prop"
            :key="item.key"
            align="center"
            :column-key="item.key"
            :width="item.width"
          >
            <template slot-scope="scope">
              <template v-if="item.slotType === 'auto'">
                <el-autocomplete
                  class="inline-input"
                  v-model="scope.row[item.prop]"
                  :fetch-suggestions="
                    (queryString, cb) => {
                      querySearchTable(queryString, cb, scope.row, item.prop)
                    }
                  "
                  :placeholder="`请输入${item.label}`"
                  @select="handleSelectTable($event, scope.row, item.prop)"
                  @blur="onBlur"
                  ><template slot-scope="{ item }">
                    <div class="name">{{ item[item.prop] }}</div>
                  </template></el-autocomplete
                >
              </template>
              <template v-else-if="item.slotType === 'input'">
                <el-input
                  v-model="scope.row[item.prop]"
                  :placeholder="`请输入${item.label}`"
                  :type="item.inputType"
                  clearable
                >
                </el-input>
              </template>
              <template v-else-if="item.slotType === 'select'">
                <el-select
                  v-model="scope.row[item.prop]"
                  :placeholder="`请选择${item.label}`"
                >
                  <el-option
                    v-for="(e, index) in item.options"
                    :key="index"
                    :label="e.label"
                    :value="e.value"
                  ></el-option>
                </el-select>
              </template>
              <template v-else-if="item.slotType === 'dateTime'">
                <el-date-picker
                  v-model="scope.row[item.prop]"
                  :type="item.dateType"
                  placeholder="选择日期时间"
                  clearable
                  value-format="timestamp"
                >
                </el-date-picker>
              </template>
              <template v-else-if="item.slotType === 'button'">
                <el-button
                  type="danger"
                  @click="deleteRow(scope.$index, scope.row)"
                  v-privilege="activeMenu + 'DELETE'"
                  disabled="false"
                >
                  删除
                </el-button>
              </template>
              <template v-else>
                <span>{{ scope.row[item.prop] }}</span>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button
          size="mini"
          type="danger"
          @click="handleClose()"
          :disabled="buttonType2 === 0 ? true : false"
          >撤 回</el-button
        >
        <el-button
          size="mini"
          type="primary"
          @click="handleClose2()"
          :disabled="buttonType1 === 0 ? true : false"
          >提 交
        </el-button>
        <el-button size="mini" type="primary" @click="delpaiche()">
          取消派车
        </el-button>
      </span>
    </el-dialog>
    <div class="main">
      <dilTable
        ref="excelDom"
        v-bind.sync="tableSel"
        @func="func"
        @selection-change="selectionChangeLn"
      >
        <el-table-column
          label="操作"
          align="center"
          width="300px"
          fixed="right"
        >
          <template slot-scope="scope">
            <div
              style="
                display: flex;
                justify-content: center;
                align-items: center;
              "
            >
              <el-button
                class="el-button--mini"
                size="mini"
                type="primary"
                @click="updatePriceMaterial(scope.row)"
                v-if="['待申报'].includes(scope.row.status)"
              >
                修改
              </el-button>
              <el-button
                class="el-button--mini"
                size="mini"
                type="danger"
                @click="withdraw(scope.row)"
                v-if="!['待申报'].includes(scope.row.status)"
              >
                请求撤回
              </el-button>
              <el-button size="mini" type="primary" @click="copy(scope.row)">
                复制
              </el-button>
              <el-button
                size="mini"
                type="primary"
                @click="operate(scope.row)"
                v-if="['待申报', '已申报'].includes(scope.row.status)"
              >
                业务操作
              </el-button>
              <el-button
                size="mini"
                type="primary"
                @click="transOrderDetails(scope.row)"
                v-if="['已制订计划'].includes(scope.row.status)"
              >
                运输详情
              </el-button>
              <el-button
                size="mini"
                type="primary"
                @click="requirementApproveDetails(scope.row)"
                v-if="['已申报', '已审批', '拒绝'].includes(scope.row.status)"
              >
                审批详情
              </el-button>
            </div>
          </template>
        </el-table-column>
      </dilTable>
    </div>
    <!-- 尾部代码块表格等 -->
    <div class="footer"></div>
    <el-dialog
      title="运单详情"
      :visible.sync="dialogVisibleTransOrder"
      width="80%"
    >
      <transOrder
        :requirementId="transRequirementId"
        :operateRole="false"
        v-if="dialogVisibleTransOrder"
      ></transOrder>
    </el-dialog>
    <el-dialog
      title="取消派车原因"
      :visible.sync="delpaicheVisible"
      width="30%"
    >
      <el-input
        v-model="delpaicheInput"
        placeholder="请输入取消派车原因"
      ></el-input>
      <el-button
        size="mini"
        type="primary"
        class="btn"
        @click="delpaicheClick()"
      >
        <i class="el-icon-search"></i>确定
      </el-button>
    </el-dialog>
    <el-dialog
      :title="approveTitle"
      :visible.sync="dialogVisibleApprove"
      width="30%"
    >
      <div>
        <el-steps
          direction="vertical"
          :active="Number(approveStepList[0].active)"
          v-if="approveStepList.length > 1"
          space="60px"
        >
          <el-step
            v-for="item in approveStepList"
            :key="item.workFlowId"
            :title="item.companyName"
            :description="`${item.approveStatus}${
              item.approveReason ? '-' + item.approveReason : ''
            }`"
            :status="item.processStatus"
          ></el-step>
        </el-steps>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import transOrder from '../transOrder/transOrder.vue'
import { toNumber } from 'xe-utils'
import { getCompanyId } from '../../app.js'
export default {
  components: {
    transOrder
  },
  data() {
    return {
      matchTransRequirementId: null,
      dialogVisible4: false,
      capacityType: '',
      formTable: {
        materialTypeName: ''
      },
      searchClickValue: null,
      matchSelection: [],
      inputLn: '',
      drawerLn2: false,
      updateIds: [],
      rowData: {},
      tableColumnList: [
        {
          type: 'index',
          label: '序号',
          prop: 'index',
          width: '40px',
          key: Math.floor(Math.random() * 1000) + '' // 止重复
        },
        {
          prop: 'materialTypeName',
          label: '业务名称',
          slotType: 'auto',
          isValidate: true,
          key: Math.floor(Math.random() * 1000) + ''
        },
        {
          prop: 'transrangeName',
          label: '业务区间',
          slotType: 'auto',
          isValidate: true,
          key: Math.floor(Math.random() * 1000) + ''
        },
        {
          prop: 'lineName',
          label: '运输路线',
          slotType: 'auto',
          isValidate: true,
          lineName: true,
          key: Math.floor(Math.random() * 1000) + ''
        },
        {
          prop: 'materialName',
          label: '物资',
          slotType: 'auto',
          // isValidate: true,
          width: '300px',
          key: Math.floor(Math.random() * 1000) + ''
        },

        {
          prop: 'capacityTypeName',
          label: '运力类型',
          slotType: 'auto',
          isValidate: true,
          key: Math.floor(Math.random() * 1000) + ''
        },
        {
          prop: 'billingType',
          label: '计费类型',
          slotType: 'select',
          isValidate: true,
          options: [
            { label: '计重', value: '计重' },
            { label: '计时', value: '计时' },
            { label: '计次', value: '计次' },
            { label: '计重且计时', value: '计重且计时' },
            { label: '计重或计时', value: '计重或计时' },
            { label: '计次且计重', value: '计次且计重' }
          ],
          key: Math.floor(Math.random() * 1000) + ''
        },
        {
          prop: 'materialNumber',
          label: '转运件数',
          slotType: 'input',
          dateType: 'number',
          key: Math.floor(Math.random() * 1000) + ''
        },
        {
          prop: 'materialWeight',
          label: '转运吨位',
          slotType: 'input',
          inputType: 'number',
          key: Math.floor(Math.random() * 1000) + ''
        },
        {
          prop: 'transTruckNumber',
          label: '转运车数',
          slotType: 'input',
          dateType: 'number',
          key: Math.floor(Math.random() * 1000) + ''
        },
        {
          prop: 'operate',
          label: '操作',
          slot: true,
          slotType: 'button',
          width: '200px',
          key: Math.floor(Math.random() * 1000) + ''
        }
      ],
      tableColumnList2: [
        {
          type: 'index',
          label: '序号',
          prop: 'index',
          width: '40px',
          key: Math.floor(Math.random() * 1000) + '' // 止重复
        },
        {
          prop: 'materialTypeName',
          label: '业务名称',
          slotType: 'auto',
          isValidate: true,
          key: Math.floor(Math.random() * 1000) + ''
        },
        {
          prop: 'transrangeName',
          label: '业务区间',
          slotType: 'auto',
          isValidate: true,
          key: Math.floor(Math.random() * 1000) + ''
        },
        {
          prop: 'lineName',
          label: '运输路线',
          slotType: 'auto',
          isValidate: true,
          lineName: true,
          key: Math.floor(Math.random() * 1000) + ''
        },
        {
          prop: 'materialName',
          label: '物资',
          slotType: 'auto',
          // isValidate: true,
          width: '300px',
          key: Math.floor(Math.random() * 1000) + ''
        },

        {
          prop: 'capacityTypeName',
          label: '运力类型',
          slotType: 'auto',
          isValidate: true,
          key: Math.floor(Math.random() * 1000) + ''
        },
        {
          prop: 'billingType',
          label: '计费类型',
          slotType: 'select',
          isValidate: true,
          options: [
            { label: '计重', value: '计重' },
            { label: '计时', value: '计时' },
            { label: '计次', value: '计次' },
            { label: '计重且计时', value: '计重且计时' },
            { label: '计次且计重', value: '计次且计重' }
          ],
          key: Math.floor(Math.random() * 1000) + ''
        },
        {
          prop: 'materialNumber',
          label: '转运件数',
          slotType: 'input',
          dateType: 'number',
          key: Math.floor(Math.random() * 1000) + ''
        },
        {
          prop: 'materialWeight',
          label: '转运吨位',
          slotType: 'input',
          inputType: 'number',
          key: Math.floor(Math.random() * 1000) + ''
        },
        {
          prop: 'transTruckNumber',
          label: '转运车数',
          slotType: 'input',
          dateType: 'number',
          key: Math.floor(Math.random() * 1000) + ''
        },
        {
          prop: 'operate',
          label: '操作',
          slot: true,
          slotType: 'button',
          width: '200px',
          key: Math.floor(Math.random() * 1000) + ''
        }
      ],
      activeMenu: window.top.localStorage.getItem('activeMenu'),
      approveTitle: '',
      dialogVisibleApprove: false,
      transRequirementId: null,
      dialogVisibleTransOrder: false,
      dialog: {
        cell: [],
        editorBox: {
          activeName: 1,
          activeName2: 1,
          nameObj: {
            companyid: {
              obj: {},
              arr: [],
              showDataArr: []
            },
            materiaid: {
              obj: {},
              arr: [],
              showDataArr: []
            },
            transRange: {
              obj: {},
              arr: [],
              showDataArr: []
            }
          },
          type: ''
        }
      },
      previewUrl: '',
      cell: [],
      dialogVisible: false,
      delpaicheInput: '',
      delpaicheVisible: false,
      alternateFields6: 0,
      buluButton: 0,
      tableData: [],
      deleteButton: 0,
      buttonType: 1,
      buttonType1: 1,
      buttonType2: 1,
      fileList: [],
      singleTableHeight: 600,
      buludialogVisible: false,
      form1: {},
      form2: {},
      drawerLn: false,
      idcount: [],
      idcount2: [],
      codecount: {},
      form3: {},
      form4: {},
      form5: {},
      dialogVisible: false,
      dialogVisible2: false,
      dialogVisible3: false,
      activeName: 'first',
      isKuang: false,
      loading: false,
      input: '',
      option: {
        // 表格请求数据的地址
        requestUrl:
          '/api/v1/ams/getproductionRequirementList?apiId=543&i=' + new Date(),
        selectionType: 'select',
        requestQuery: {},
        compareField: 'auditNumber',
        showFilter: false
        // height: 350
      },
      optionNoMerge: {
        // 表格请求数据的地址
        requestUrl:
          '/api/v1/ams/getproductionRequirementList?apiId=656&i=' + new Date(),
        selectionType: 'select',
        requestQuery: {},
        showFilter: false
        // height: 350
      },
      optionSearchClick: {
        requestUrl: '',
        requestQuery: {
          deleted: 0
        },
        selectionType: 'radio',
        reserveSelection: false,
        showFilter: false
        // height: 350
      },
      tableTitle: '生产运输需求',
      showFilter: true,
      searchFormId: 480,
      addFormId: 464,
      approveStepList: []
    }
  },
  computed: {
    tableSel() {
      console.log(this.form1, 'form1')
      if (this.form1.requirementStatus == '待申报') {
        this.onclick()
        return this.option
      } else {
        this.onclick()
        return this.optionNoMerge
      }
    }
  },
  created() {
    this.activeMenu = window.top.localStorage.getItem('activeMenu')
    // 接收路由参数
    let that = this
    if (that.$route.query.businessType) {
      that.form1.businessType = that.$route.query.businessType
      that.form2.businessType = that.$route.query.businessType
    }
    let businessCompanyId = getCompanyId()
    // that.form1.businessCompanyId = businessCompanyId
    that.form2.businessCompanyId = businessCompanyId
    // if (localStorage.getItem('roleCodes').includes('admin')) {
    //   this.searchFormId = 480
    //   this.addFormId = 464
    // } else {
    //   this.searchFormId = 605
    //   this.addFormId = 606

    // }
  },
  mounted() {
    let that = this
    if (that.$route.query.capacityType) {
      that.form1.capacityTypes = that.$route.query.capacityType.split(',')
      that.capacityType = that.$route.query.capacityType
    }
    // this.onclick()
  },
  directives: {
    'autocomplete-scroll': {
      bind(el, binding, vnode) {
        // 此处为了简单，直接判断触底了
        function handleScroll(e) {
          let isBottom =
            e.target.clientHeight + e.target.scrollTop >
            e.target.scrollHeight - 1
          //console.log(e.target.clientHeight + e.target.scrollTop, e.target.scrollHeight, vnode.context.loading, vnode.context, 'debounce')
          if (isBottom && !vnode.context.loading) {
            // console.log(e.target.clientHeight + e.target.scrollTop, e.target.scrollHeight, vnode.context.loading, 'debounce')
            binding.value(vnode)
          }
        }

        // 监听滚动
        let wrapDom = el.querySelector('.el-autocomplete-suggestion__wrap')
        el.__handleScroll__ = handleScroll
        el.__wrapDom__ = wrapDom
        wrapDom.addEventListener('scroll', handleScroll, false)
      },

      unbind(el, binding, vnode) {
        console.log('unbind')
        // 解除事件监听
        el.__wrapDom__.removeEventListener('scroll', el.__handleScroll__, false)
      }
    }
  },
  methods: {
    matchSubmit() {
      if (this.matchSelection == 0) {
        return this.$message.error('请选择需求！')
      }
      console.log(this.matchSelection)
      console.log(this.matchTransRequirementId)
      let model = {
        model: {
          amsFixedNeeds: this.matchSelection.map((res) => res.fixedNeedsId),
          transRequirementId: this.matchTransRequirementId
        }
      }
      this.axios
        .post('/api/v1/ams/addAmsFixedBindRequirement', model)
        .then((res) => {
          if (res.data.status == 'succeed') {
            this.$message({
              type: 'success',
              message: '操作成功!'
            })
          }
        })
    },
    getInputFocus(event) {
      event.currentTarget.select()
    },
    selectChangeForm2(val) {
      if (val.businessCompanyId) {
        console.log('val=>', val)
        this.form2.parentCompanyId = val.businessCompanyId[0].parentCompanyId
      }
    },
    async handleScroll(val) {
      console.log(val)
      console.log(val.data.attrs.index, 'val.data')
      let index = val.data.attrs.index
      let prop = val.data.ref
      let url = ''
      let queryMap = {
        index: this.$refs[prop][index].$props.value,
        lastIndex: this.$refs[prop][index].$data.suggestions.slice(-1)[0].value
      }
      if (prop == 'organization' || 'materialTypeName') {
        url = '/api/v1/uc/getMaterialTypeByLike'
        queryMap.remark = '生产'
        queryMap.companyType = '业务单位'
      }
      if (prop == 'transrangeName') {
        if (this.form2.businessType && this.form2.businessType == 12) {
          queryMap.remark = '生产'
          queryMap.isNc = 'NC'
        }
        url = '/api/v1/uc/getTransRangeByLike'
        queryMap.companyType = '业务单位'
      }
      if (prop == 'lineName') {
        url = '/api/v1/uc/getLineByLike'
        queryMap.lineType = '生产'
      }
      if (prop == 'materialName') {
        url = '/api/v1/uc/getMaterialByLike'
      }
      if (prop == 'capacityTypeName') {
        url = '/api/v1/uc/getCapacityTypeByLike'
      }
      this.axios.post(url, queryMap).then((res) => {
        let data = res.data.data
        if (data.length == 0) {
        } else {
          this.$refs[prop][index].$data.suggestions.push(...data)
        }
      })
    },
    copyRow(index, row) {
      this.tableData.push({
        ...row,
        index: this.tableData.length + 1
      })
    },
    clearTableItem(prop) {
      console.log(prop)
      console.log('prop')
      delete this.formTable[prop]
    },
    onclickLnSearchClick() {
      this.optionSearchClick.requestQuery = {}
    },
    async handClickSearchClick() {
      if (this.searchClickValue) {
        if (
          !this.searchClickValue.forwardingPointId &&
          !this.searchClickValue.receivingPointId
        ) {
          return this.$message.error('请选择运单')
        }
        //查询装货点
        let map = {
          startPointId: this.searchClickValue.forwardingPointId,
          endPointId: this.searchClickValue.receivingPointId
        }
        let res = await this.axios.post(
          '/api/v1/rms/queryInsertTransRange',
          map
        )
        if (!res.data.succeed) {
          return this.$message.error('查询装卸点失败')
        }
        if (this.form2.sourceOrderId) {
          this.tableData.forEach((item, index) => {
            if (item.isOrder) {
              console.log(item, 'item')
              let temp = {
                isOrder: true,
                transrangeName: res.data.data.transRangeName,
                operationRange: res.data.data.transRangeId,
                operationRangeId: res.data.data.transRangeId + '',
                operationRangeName: res.data.data.transRangeName,
                shippingPointId: res.data.data.startPointId,
                receivingPointId: res.data.data.endPointId,
                materialName: this.searchClickValue.materialName,
                materialId: this.searchClickValue.materialId,
                index: this.tableData.length + 1
              }
              this.$set(this.tableData, index, temp)
              // this.formTable = temp;
              console.log(this.tableData, 'tableData22')
            }
          })
        } else {
          this.tableData.push({
            isOrder: true,
            transrangeName: res.data.data.transRangeName,
            operationRange: res.data.data.transRangeId,
            operationRangeId: res.data.data.transRangeId + '',
            operationRangeName: res.data.data.transRangeName,
            shippingPointId: res.data.data.startPointId,
            receivingPointId: res.data.data.endPointId,
            materialName: this.searchClickValue.materialName,
            materialId: this.searchClickValue.materialId,
            index: this.tableData.length + 1
          })
          // this.formTable = {
          //   isOrder:true,
          //   transrangeName:res.data.data.transRangeName,
          //   operationRange: res.data.data.transRangeId,
          //   operationRangeId:res.data.data.transRangeId+"",
          //   operationRangeName:res.data.data.transRangeName,
          //   shippingPointId :res.data.data.startPointId,
          //   receivingPointId : res.data.data.endPointId,
          //   materialName: this.searchClickValue.materialName,
          //   materialId: this.searchClickValue.materialId,
          //   index: this.tableData.length + 1,
          // };
        }
        // this.form2 = this.searchClickValue;
        this.$set(this.form2, 'orderId', this.searchClickValue.orderId)
        this.$set(
          this.form2,
          'orderChildId',
          this.searchClickValue.orderChildId
        )
        this.$set(this.form2, 'order', this.searchClickValue.serialNumber)
        console.log(this.tableData)
      }
      this.drawerLn2 = false
    },
    selectionChangeLn2(selection) {
      console.log(selection, 'selection')
      this.searchClickValue = selection
    },
    selectionChangeLn3(selection) {
      this.matchSelection = selection
    },
    searchClick(val) {
      console.log(val)
      this.drawerLn2 = true
      this.optionSearchClick.requestUrl = val.url
    },
    clearChange(item) {
      console.log(item, 'item')
      Object.keys(item).forEach((i) => {
        delete this.form1[i]
      })
    },
    clearAll() {
      this.form2 = {}
      this.tableData = []
    },
    deleteRow(index, row) {
      console.log(index, 'index')
      this.tableData.splice(index, 1)
    },
    defaultValueGet(item) {
      this.onclick()
      console.log(item)
    }, //取消派车
    handleSelectTable(item, row, prop, index) {
      console.log(index, 'index')
      // this.$set(this.formTable,prop,item.text)
      // console.log(this.formTable,"formTable");

      if (prop == 'organization' || prop == 'materialTypeName') {
        row.materialTypeName = item.operationsName
        row.operationsNameId = item.operationsNameId
      }
      if (prop == 'transrangeName') {
        row.transrangeName = item.operationRangeName
        row.operationRangeName = item.operationRangeName //解决
        row.operationRange = item.operationRangeId
        row.operationRangeId = item.operationRangeId
        row.shippingPointId = item.shippingPointId
        row.receivingPointId = item.receivingPointId
      }
      if (prop == 'lineName') {
        console.log(row)
        row.lineName = item.lineName
        row.lineId = item.lineId
      }
      if (prop == 'materialName') {
        row.materialName = item.materialName
        row.materialId = item.materialId
      }
      if (prop == 'capacityTypeName') {
        row.capacityTypeName = item.capacityTypeName
        row.capacityTypeId = item.capacityTypeId
      }

      row = { ...row, ...item }
    },
    querySearchTable(queryString, cb, row, prop) {
      console.log(row[prop], 'prop')
      console.log(queryString, 'queryString')
      let url = ''
      let queryMap = {
        // lastIndex:0,
        index: row[prop]
      }
      if (prop == 'organization' || 'materialTypeName') {
        url = '/api/v1/uc/getMaterialTypeByLike'
        queryMap.remark = '生产'
        queryMap.companyType = '业务单位'
      }
      if (prop == 'transrangeName') {
        if (this.form2.businessType && this.form2.businessType == 12) {
          queryMap.remark = '生产'
          queryMap.isNc = 'NC'
        }
        url = '/api/v1/uc/getTransRangeByLike'
        queryMap.companyType = '业务单位'
      }
      if (prop == 'lineName') {
        url = '/api/v1/uc/getLineByLike'
        queryMap.lineType = '生产'
      }
      if (prop == 'materialName') {
        url = '/api/v1/uc/getMaterialByLike'
      }
      if (prop == 'capacityTypeName') {
        url = '/api/v1/uc/getCapacityTypeByLike'
        queryMap.capacityTypeNameList = this.form1.capacityTypes
      }

      this.axios.post(url, queryMap).then((res) => {
        let data = res.data.data
        console.log('querySearchTable===>', data)
        if (data.length == 0) {
          let item = {}
          item['prop'] = prop
          item[prop] = '暂无数据,请核验或注册数据'
          cb([item])
        } else {
          cb(data)
        }
      })
    },
    onBlur() {},
    addRow() {
      this.tableData.push({
        index: this.tableData.length + 1,
        carrierName: '',
        materialNumber: null,
        transTruckNumber: null,
        dueTime: null,
        materialTypeName: '',
        operate: '',
        transTruckNumber: '',
        materialWeight: '',
        billingType: '',
        capacityTypeName: '',
        materialName: '',
        lineName: '',
        transrangeName: ''
      })
    },
    //批量申报
    batchSubmit() {
      if (this.idcount.length == 0) {
        this.$message({
          type: 'warning',
          message: '请先选择需要申报的数据',
          duration: 2000
        })
        return
      }
      this.$confirm('是否确认批量提交?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let map = {
          approve: 'ok',
          mapList: this.idcount
        }
        this.axios
          .post('/api/v1/ams/productionRequirementChangeList', map)
          .then((res) => {
            if (res.data.status == 'succeed') {
              this.$message({
                type: 'success',
                message: res.data.message
              })

              this.onclick()
            } else {
              this.$message({
                type: 'error',
                message: res.data.message
              })

              this.onclick()
            }
          })
      })
    },
    //查看审批详情
    requirementApproveDetails(row) {
      this.approveTitle = row.serialNumber + '-' + '审批详情'
      this.transRequirementId = row.transRequirementId
      let map = {
        transRequirementId: row.transRequirementId
      }
      this.dialogVisibleApprove = true
      this.axios
        .post('/api/v1/ams/requirementApproveDetails', map)
        .then((res) => {
          this.approveStepList = res.data.data
        })
    },
    //查看运输详情
    transOrderDetails(row) {
      this.transRequirementId = row.transRequirementId
      this.dialogVisibleTransOrder = true
      console.log(row.transRequirementId)
    },
    handClick() {
      let that = this
      let change = that.form2.alternateFields1
      that.$set(that.form2, 'alternateFields1', change)
      that.form2.alternateFields1 = that.codecount.RULES_ID
      that.form2.operationRange = that.codecount.TRANS_RANGE_ID
      that.form2.businessCompanyId = that.codecount.COMPANY_ID
      that.form2.operationsNameId = that.codecount.MATERIAL_ID
      that.drawerLn = false
    },
    onclickLn() {
      this.optionLn.requestQuery = JSON.parse(JSON.stringify(this.form1))
    },
    showLineDrawer(scope) {
      this.drawerLn = true
    },
    selectionChangeLnCode(selection) {
      let that = this
      that.codecount = selection
    },
    // fileRemoveHandle4(file, fileList) {
    //   let that = this
    //   console.log('file,fileList' + file, fileList)
    //   // if (file.id) {
    //   //     this.instFilePics.push(file.id);
    //   // }
    //   that.fileList = fileList
    // },
    selectionChangeLn(selection) {
      let that = this
      that.idcount = selection
      that.idcount2 = []
      console.log('selection======>', selection)
      for (let item of that.idcount) {
        that.idcount2 += item.transRequirementId + ','
        if (item.status === '已审核' || item.status === '已申报') {
          that.deleteButton = 0
        } else {
          that.deleteButton = 1
        }
      }
      for (let item of that.idcount) {
        that.idcount2 += item.requirementChildId
        if (item.billingType === '计次') {
          that.buluButton = 1
        } else {
          that.buluButton = 0
        }
      }
    },
    validateForms() {
      this.tableData.forEach((item, index) => {
        const formRef = this.$refs[`tableForm_${index}`]
        console.log(formRef[0])
        if (formRef) {
          formRef[0].validate((valid) => {
            console.log(valid, 'valid')
            return valid
          })
        }
      })
    },
    // validateForm(val) {
    //   console.log( eval('this.$refs.tableForm' + val)[0]);
    //   let flag = null
    //     eval('this.$refs.tableForm' + val)[0].validate(valid => {
    //     console.log(valid,"valid");
    //     if (!valid) {
    //       flag = true
    //     } else {
    //       flag = false
    //     }
    //   })
    //   return flag
    // },
    submitBut() {
      let flag = true
      this.$refs['tableForm_1'].forEach((item) => {
        item.validate((valid) => {
          flag = valid && flag
        })
      })
      let that = this
      if (this.$refs['form2'].validateForm() && flag) {
        if (
          new Date(that.form2.requirementStartTime).getTime() >
          new Date(that.form2.requirementEndTime).getTime()
        ) {
          this.$message({
            message: '用车开始时间不能大于用车结束时间',
            type: 'warning'
          })
          return
        }
        if (
          new Date(that.form2.requirementEndTime).getTime() -
            60 * 60 * 1000 * 13 >
          new Date(that.form2.requirementStartTime).getTime()
        ) {
          this.$message({
            message: '用车起止时间不能超过13小时',
            type: 'warning'
          })
          return
        }
        const startTime = new Date(that.form2.requirementStartTime)
        const endTime = new Date(that.form2.requirementEndTime)
        const startHour = startTime.getHours()
        const endHour = endTime.getHours()
        const endMinutes = endTime.getMinutes()
        const endSeconds = endTime.getSeconds()
        let startArr1 = [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
        let endArr1 = [8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19]
        let startArr2 = [19, 20, 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 6, 7, 8]
        let endArr2 = [19, 20, 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 6, 7, 8]
        if (startArr1.includes(startHour) && endArr1.includes(endHour)) {
          if (endHour == 19 && (endMinutes > 0 || endSeconds > 0)) {
            this.$message({
              message: '用车结束时间为19点时,请勿选择时分秒',
              type: 'warning'
            })
            return
          }
        } else if (startArr2.includes(startHour) && endArr2.includes(endHour)) {
          if (endHour == 8 && (endMinutes > 0 || endSeconds > 0)) {
            this.$message({
              message: '用车结束时间为8点时,请勿选择时分秒',
              type: 'warning'
            })
            return
          }
        } else {
          this.$message({
            message:
              '用车起止时间不符合要求,白班在8点到19点之间,夜班在19点到8点之间',
            type: 'warning'
          })
          return
        }
        if (true) {
          if (that.dialog.editorBox.type === 'ADD') {
            that
              .$confirm('是否保存?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
              .then(() => {
                that.dataSave()
              })
              .catch(() => {})
          } else {
            that
              .$confirm('是否修改?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
              })
              .then(() => {
                that.dataSave()
              })
              .catch(() => {})
          }
        }
      }
    },
    //撤回
    handleClose() {
      let that = this
      that
        .$confirm('是否撤回?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.valueUpdate(0)
        })
        .catch(() => {})
    },
    //提交
    handleClose2() {
      let that = this
      that
        .$confirm('是否提交?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          that.valueUpdate(1)
        })
        .catch(() => {})
    },
    //导出方法
    exportAllExcel() {},
    // 导入方法
    beforeUpload(event, file, fileList) {
      let _this = this
      let formData = new FormData()
      formData.append('file', file.raw)
      _this.loading = true
      this.axios
        .post('/api/v1/rms/readExcel/', formData, {
          headers: { 'Content-Type': 'multipart/form-data' }
        })
        .then((res) => {
          console.log('res.code=======>', res)
          if (res.data.code === '0') {
            this.$message.success('操作成功')
            _this.onclick()
          } else {
            this.$message.error(res.message)
          }
          _this.loading = false
        })
        .catch(() => {
          _this.loading = false
        })
    },
    copy(row) {
      console.log('复制')
      let that = this
      that.dialog.editorBox.type = 'ADD'
      that.dialogVisible = true
      that.dialog.editorBox.activeName = '1'
      if (this.form1.requirementStatus == '待申报') {
        that.tableData = that.cell
          .filter((i) => i.auditNumber == row.auditNumber)
          .map((item, index) => {
            //序号
            item.index = index + 1
            return item
          })
      } else {
        that.tableData = [row].map((item, index) => {
          //序号
          item.index = index + 1
          return item
        })
      }
      let { index, ...temp } = {
        ...row,
        alternateFields8: Number(row.alternateFields8)
      }
      that.form2 = temp
      this.form2.sbddList = []
      if (row.sbdd) {
        row.sbdd.split(',').forEach((item) => {
          this.form2.sbddList.push(toNumber(item))
        })
      }
      let submitBut = {
        type: 'add'
      }
      this.axios
        .post('/api/v1/ams/getSerialNumber', submitBut)
        .then((res) => {
          if (res.data.code == '0') {
            // this.form2.serialNumber = res.data.data.serialNumber
            // this.form2.transRequirementId = res.data.data.transRequirementId
            this.$set(this.form2, 'serialNumber', res.data.data.serialNumber)
            // this.$set(this.form2,"transRequirementId",res.data.data.transRequirementId);
          } else {
          }
        })
        .catch(() => {
          this.isHaveArea = false
        })
      // that.form2.transRequirementId = row.transRequirementId
      // that.form3.shippingCompanyId = row.shippingCompanyId
      // that.form2.transShipmentType = row.transShipmentType
      // that.form2.receivingPointId = row.receivingPointId
      // that.form2.materialId = row.materialId

      // that.form2.businessType = row.businessType
      // that.form2.billingType = row.billingType
      // that.form2.requirementContactPhone = row.requirementContactPhone
      // that.form2.requirementContact = row.requirementContact
      // that.form2.dueTime = row.dueTime
      // that.form2.alternateFields1 = row.rulesId
      // that.form2.shippingPointId = row.shippingPointId
      // ;(that.form2.operationRange = row.transrangeId), //业务区间
      //   (that.form2.businessCompanyId = row.businessCompanyId), //用车单位
      //   (that.form2.operationsNameId = row.materialTypeId), //业务名称
      //   (that.form3.lineId = row.lineId), //作业路径
      //   (that.form2.transMode = row.transMode), //运输方式
      //   (that.form3.receivingCompanyId = row.receivingCompanyId), //收获单位
      //   (that.form2.capacityTypeId = row.capacityTypeId), //运力类型
      //   (that.form2.requirementStartTime = row.requirementStartTime), //用车起始时间
      //   (that.form2.requirementEndTime = row.requirementEndTime), //用车结束时间
      //   (that.form2.materialWeight = row.materialWeight), //物资吨位
      //   (that.form3.transTruckNumber = row.transTruckNumber), //承运车数
      //   (that.form3.controlRate = row.controlRate), //控制率
      //   (that.form3.controlMode = row.controlMode), //控制方式
      //   (that.form3.printStampList = row.printStampList), //磅单打印
      //   (that.form3.nuclearLoadControl = row.nuclearLoadControl), //核载控制
      //   (that.form3.theoryWeight = row.theoryWeight), //理重控制
      //   (that.form3.isDomestic = row.isDomestic), //是否内销
      //   (that.form3.insertUpdateRemark = row.isDomestic) //
      //   (that.form2.alternateFields8 = row.alternateFields8) //新增
    },

    //操作
    operate(row) {
      let that = this
      that.dialogVisible2 = true
      that.dialog.editorBox.activeName2 = '1'
      that.rowData = row
      that.form4.transRequirementId = row.transRequirementId
      that.form4.shippingCompanyId = row.shippingPointName
      that.form4.transShipmentType = row.transShipmentType
      that.form4.receivingPointId = row.receivingPointName
      that.form4.requirementType = row.requirementType
      that.form4.materialId = row.materialName
      that.form4.businessType = row.businessType
      that.form4.billingType = row.billingType
      that.form4.requirementContactPhone = row.requirementContactPhone
      that.form4.requirementContact = row.requirementContact
      that.form4.dueTime = row.dueTime
      that.form4.alternateFields1 = row.rulesCode
      that.form4.shippingPointId = row.shippingPointName
      that.form4.operationRange = row.transrangeName //业务区间
      that.form4.businessCompanyId = row.organization //用车单位
      that.form4.operationsNameId = row.materialTypeName //业务名称
      that.form4.lineId = row.lineName //作业路径
      that.form4.transMode = row.transMode //运输方式
      that.form4.receivingCompanyId = row.receiveCompanyName //收获单位
      that.form4.capacityTypeId = row.capacityTypeName //运力类型
      that.form4.requirementStartTime = row.requirementStartTime //用车起始时间
      that.form4.requirementEndTime = row.requirementEndTime //用车结束时间
      that.form4.materialWeight = row.materialWeight //物资吨位
      that.form4.transTruckNumber = row.transTruckNumber //承运车数
      that.form4.controlRate = row.controlRate //控制率
      that.form4.controlMode = row.controlModeStr //控制方式
      that.form4.printStampList = row.printStampListStr //磅单打印
      that.form4.nuclearLoadControl = row.nuclearLoadControlStr //核载控制
      that.form4.theoryWeight = row.theoryWeight //理重控制
      that.form4.isDomestic = row.isDomestic //是否内销
      that.form4.insertUpdateRemark = row.insertUpdateRemark //
      that.form4.alternateFields2 = row.alternateFields2
      let aa = that.cell.filter((i) => i.auditNumber == row.auditNumber)
      console.log('hat.cell.filter(i=>i.auditNumber==row.auditNumber)====>', aa)
      this.tableData = aa
      if (row.status === '待申报' || row.status === '已撤回') {
        that.buttonType1 = 1
      } else {
        that.buttonType1 = 0
      }

      if (row.status === '已申报' || row.status === '已审批') {
        that.buttonType2 = 1
      } else {
        that.buttonType2 = 0
      }
      console.log('row====>', row)
    },
    func(res) {
      console.log('res====>', res)
      this.loading = false
      this.isKuang = false
      let label = []
      for (let item of res.columnData) {
        label += item.label + ','
      }
      this.dialog.cell = label
      this.cell = res.list
    },
    onclick(val) {
      if (val) {
        this.addFormId = 464
        delete this.form1.alternateFields15
        if (this.form1.insertTimeRange1) {
          this.form1.insertTimeRange = this.form1.insertTimeRange1
          delete this.form1.insertTimeRange1
        }
      }
      console.log('onclick')
      // let {transrangeName,...temp} = this.form1

      this.option.requestQuery = JSON.parse(JSON.stringify(this.form1))
      this.optionNoMerge.requestQuery = JSON.parse(JSON.stringify(this.form1))
    },
    onclickFixed() {
      this.addFormId = 690
      // let {transrangeName,...temp} = this.form1
      this.form1.alternateFields15 = 1

      console.log(this.form1)
      if (this.form1.insertTimeRange) {
        this.form1.insertTimeRange1 = this.form1.insertTimeRange
        delete this.form1.insertTimeRange
      }
      console.log(this.form1)
      this.option.requestQuery = JSON.parse(JSON.stringify(this.form1))
    },
    logicDelete() {
      if (this.idcount.length == 0) {
        this.$message({
          type: 'warning',
          message: '请选择要删除的数据!'
        })
        return
      }
      this.$confirm(
        '是否删除(系统自动过滤无法删除的需求-仅待申报能删除)',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }
      )
        .then(() => {
          let that = this
          let idcount2 = []
          let idcount3 = []
          for (let item of that.idcount) {
            idcount2 += item.transRequirementId + ','
            console.log('idcount2====>', idcount2)
          }
          let SubmitData = {
            transRequirementId: idcount2
          }
          that.axios
            .post('/api/v1/ams/getProductiveRequirementDelete/', SubmitData)
            .then((res) => {
              if (res.data.code == '0') {
                that.$message.success('删除成功')
                that.dialogVisible = false
                that.isHaveArea = false
                that.onclick()
              } else {
                that.$message.error('删除失败')
                that.isHaveArea = false
                that.dialogVisible = false
              }
            })
            .catch(() => {
              that.$message.error('删除失败')
              that.isHaveArea = false
            })
        })
        .catch(() => {
          this.$message.info('用户取消操作')
        })
    },
    exportAllExcel() {
      var today = new Date()
      var year = today.getFullYear() //获取年份
      var month = today.getMonth() + 1 //获取月份
      var day = today.getDate() //获取日期
      this.tableTitle = year + '-' + month + '-' + day + '实时库存'
      this.loading = true
      this.isKuang = true
      let deleted = 0
      let submitBut = {
        deleted: deleted
      }
      if (this.input) {
        this.axios
          .post(
            '/api/v1/wms/wmsgridmaterialsList?apiId=544&deleted=0&i=' +
              this.input +
              '&i=' +
              new Date(),
            submitBut
          )
          .then((res) => {
            console.log(res.data.data)
            this.exportAllList = res.data.data.list
            this.noSettleDetailsColumn = res.data.data.columnData
            this.exportAllReportToExcel(
              this.tableTitle,
              this.exportAllList,
              this.noSettleDetailsColumn
            )
          })
      } else {
        this.axios
          .post(
            '/api/v1/wms/wmsgridmaterialsList?apiId=544&i=' + new Date(),
            submitBut
          )
          .then((res) => {
            console.log(res.data.data)
            this.exportAllList = res.data.data.list
            this.noSettleDetailsColumn = res.data.data.columnData
            this.exportAllReportToExcel(
              this.tableTitle,
              this.exportAllList,
              this.noSettleDetailsColumn
            )
          })
      }

      this.loading = false
    },
    //导出excel
    exportAllReportToExcel(tableTitle, dataArr, columnData) {
      var title = tableTitle
      let tHeader = []
      let filterVal = []
      columnData.forEach((e1) => {
        if (tHeader.indexOf(e1.label) === -1) {
          tHeader.push(e1.label)
        }
        if (filterVal.indexOf(e1.prop) === -1) {
          filterVal.push(e1.prop)
        }
      })
      //导出为excel
      this.downloadLoading = true
      require.ensure([], () => {
        const {
          export_json_to_excel
        } = require('@/assets/excel/Export2Excel.js') //这里必须使用绝对路径，使用@/+存放export2Excel的路径
        // let list = this.$refs.excelDom.dataTabel;
        let data = dataArr.map((v) => filterVal.map((j) => v[j])) //3.formatJson格式转换
        export_json_to_excel(tHeader, data, title) // (title)导出的表格名称
      })
    },
    //修改
    updatePriceMaterial(row) {
      let that = this
      that.dialog.editorBox.activeName = '1'
      that.dialog.editorBox.type = 'PUT'
      that.dialogVisible = true
      row.key = 1
      if (
        row.status === '已申报' ||
        row.status === '已审批' ||
        row.status === '已制订计划'
      ) {
        that.$message.error('该需求已申报或审批，无法修改！')
        that.buttonType = 0
      } else {
        that.buttonType = 1
      }
      this.tableData = that.cell
        .filter((i) => i.auditNumber == row.auditNumber)
        .map((item, index) => {
          if (item.isDomestic == '是') {
            item.isDomestic = '1'
          } else {
            item.isDomestic = '0'
          }
          item.index = index + 1
          return item
        })
      console.log('tableData====>', this.tableData)
      that.updateIds = that.cell
        .filter((i) => i.auditNumber == row.auditNumber)
        .map((item) => item.transRequirementId + '')
      let { index, ...temp } = {
        ...row,
        alternateFields8: Number(row.alternateFields8)
      }
      that.form2 = temp
      this.form2.sbddList = []
      if (row.sbdd) {
        row.sbdd.split(',').forEach((item) => {
          this.form2.sbddList.push(toNumber(item))
        })
      }
    },
    withdraw(row) {
      this.$prompt('请输入撤回理由', '提示', {
        cancelButtonText: '取消',
        confirmButtonText: '确定'
      }).then((value) => {
        if (value.value) {
          row.reason = value.value
          this.axios
            .post('/api/v1/ams/withdrawRequirement', row)
            .then((res) => {
              if (res.data.status == 'succeed') {
                this.$message({
                  type: 'success',
                  message: '操作成功'
                })
                this.onclick()
              } else {
                this.$message({
                  type: 'error',
                  message: res.data.data
                })
              }
            })
        } else {
          this.$message({
            type: 'error',
            message: '请输入撤回理由'
          })
        }
      })
    },
    //状态修改
    valueUpdate(sum) {
      let that = this

      if (sum == 1) {
        let SubmitData = {
          transRequirementId: that.form4.transRequirementId,
          alternateFields2: that.form4.alternateFields2,
          approve: 'ok',
          deleted: 1
          // ...that.rowData
        }

        let map = {
          approve: 'ok',
          mapList: that.cell.filter(
            (i) => i.auditNumber == that.rowData.auditNumber
          )
        }
        console.log(map)
        that.axios
          .post('/api/v1/ams/productionRequirementChangeList', map)
          .then((res) => {
            if (res.data.code == '0') {
              that.$message.success('提交成功')
              that.dialogVisible2 = false
              that.isHaveArea = false
              that.onclick()
            } else {
              that.$message.error('提交失败')
              that.isHaveArea = false
              that.dialogVisible2 = false
            }
          })
          .catch(() => {
            that.$message.error('提交失败')
            that.isHaveArea = false
          })
      } else {
        let SubmitData2 = {
          transRequirementId: that.form4.transRequirementId,
          alternateFields2: that.form4.alternateFields2,
          withdraw: 'no'
        }
        that.axios
          .post('/api/v1/ams/productionRequirementChange/', SubmitData2)
          .then((res) => {
            if (res.data.code == '0') {
              that.$message.success('撤回成功')
              that.dialogVisible2 = false
              that.isHaveArea = false
              that.onclick()
            } else {
              that.$message.error('撤回失败')
              that.isHaveArea = false
              that.dialogVisible2 = false
            }
          })
          .catch(() => {
            that.$message.error('撤回失败')
            that.isHaveArea = false
          })
      }
    },
    dataSave() {
      let that = this
      let obj = {
        businessCompanyId: that.form2.businessCompanyId,
        businessType: that.form2.businessType,
        requirementStartTime: that.form2.requirementStartTime,
        requirementEndTime: that.form2.requirementEndTime,
        requirementType: that.form2.requirementType,
        dueTime: that.form2.dueTime,
        requirementContact: that.form2.requirementContact,
        requirementContactPhone: that.form2.requirementContactPhone,
        controlMode: that.form2.controlMode,
        controlRate: that.form2.controlRate,
        alternateFields8: that.form2.alternateFields8,
        serialNumber: that.form2.serialNumber,
        insertUpdateRemark: that.form2.insertUpdateRemark
      }
      this.tableData = this.tableData.map((i) => {
        return {
          ...i,
          ...obj
        }
      })
      let SubmitData = {
        ...that.form2,
        tableData: that.tableData,
        updateIds: that.updateIds
      }
      if (that.dialog.editorBox.type === 'ADD') {
        that.axios
          .post('/api/v1/ams/productionRequirementAdd', SubmitData)
          .then((res) => {
            if (res.data.code == '0') {
              that.dialogVisible = false
              that.isHaveArea = false
              that.$message({
                type: 'success',
                message: res.data.message,
                duration: 2000
              })
              // that.$refs.form2.resetFields();
              console.log('that.$refs.form2=========>', that.$refs.form2)
              that.onclick()
            } else {
              that.$message({
                type: 'error',
                message: res.data.message,
                duration: 2000
              })
              // that.isHaveArea = false
              // that.dialogVisible = false
            }
          })
          .catch((err) => {
            that.$message({
              type: 'error',
              message: err,
              duration: 2000
            })
            that.isHaveArea = false
          })
      } else {
        that.axios
          .post('/api/v1/ams/productionRequirementBatchUpdate', SubmitData)
          .then((res) => {
            if (res.data.code == '0') {
              that.$message.success('修改成功')
              that.dialogVisible = false
              that.isHaveArea = false
              that.onclick()
            } else {
              that.$message.error(res.data.message)
              that.isHaveArea = false
              // that.dialogVisible = false
            }
          })
      }
    },
    //文件预览
    preview() {
      let that = this
      let parmas = {
        filename: '应急操作手册.docx',
        filepath: '/应急预案/应急操作手册.docx'
      }
      let url = '/api/v1/systemfiles/previewfile/'
      let type = 'text/html'
      let responseType = 'application/json'
      let fileExtension = '应急操作手册.docx'
      that.axios.post(url, parmas).then(function (res) {
        if (res.data.code === '0') {
          let urlObject = window.URL || window.webkitURL || window
          // 将二进制流转为blob
          let blob = new Blob([res], { type: type })
          if (fileExtension !== 'pdf') {
            blob = new Blob([res.data.data], { type: type })
          }
          // if (typeof window.navigator.msSaveBlob !== 'undefined') {
          //   // 兼容IE，window.navigator.msSaveBlob：以本地方式保存文件
          //   window.navigator.msSaveBlob(blob, decodeURI(fileName))
          // } else {
          // 创建新的URL并指向File对象或者Blob对象的地址
          let blobURL = urlObject.createObjectURL(blob)
          that.dialogVisible3 = true
          that.previewUrl = blobURL
          that.loading = false
          setTimeout(() => {
            urlObject.revokeObjectURL(blobURL)
          }, 1000)
        } else {
          that.$message.error('预览失败')
          that.loading = false
        }
      })
    },
    btnclick() {
      this.dialog.editorBox.type = 'ADD'
      console.log('reff=========', this.form1)
      this.dialog.editorBox.activeName = '1'
      this.dialogVisible = true
      this.buttonType = 1
      let submitBut = {
        type: 'add'
      }
      this.axios
        .post('/api/v1/ams/getSerialNumber', submitBut)
        .then((res) => {
          if (res.data.code == '0') {
            // this.form2.serialNumber = res.data.data.serialNumber
            // this.form2.transRequirementId = res.data.data.transRequirementId
            this.$set(this.form2, 'serialNumber', res.data.data.serialNumber)
            // this.$set(this.form2,"transRequirementId",res.data.data.transRequirementId);
          } else {
          }
        })
        .catch(() => {
          this.isHaveArea = false
        })
    },
    qjnyClick() {
      console.log('this.idcount', this.idcount)
      if (this.idcount.length > 1) {
        this.$message.error('只允许勾选一条数据上传！')
      }
      console.log(this.idcount[0], 'this.idcount.length[0]')

      this.$confirm('此操作不可撤销, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          this.axios
            .post('/api/v1/ams/qjnyChange', this.idcount[0])
            .then((res) => {
              if (res.data.status == 'succeed') {
                this.$message({
                  type: 'success',
                  message: '操作成功!'
                })
                this.visible = false
                this.onclick()
              } else {
                this.$message.error(res.data.message)
              }
            })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    }
  }
}
</script>
<style lang="scss" scoped>
td .el-button--mini {
  padding: 4px 16px;
}

// .el-input--mini {
//   width: 88%;
// }

// .el-form-item__label {
//   width: 30%;
// }
.transRequirementClass {
  .top {
    margin-left: 5px;
    margin-top: 5px;
    // height: 100%;
  }

  .elDivider {
    height: 100%;
  }

  .buttonModel {
    margin-top: 5px;
    display: flex;
    justify-content: space-between;
    align-items: center;

    .operation {
      margin-left: 10px;
    }

    .search {
      margin-right: 10px;
    }

    height: 100%;
  }

  .main {
    margin-left: 5px;
    margin-top: 5px;
  }
}
</style>
