<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      :inline="true"
      v-show="showSearch"
      label-width="88px">
      <el-form-item label="任务编码" prop="taskCode">
        <el-input
          v-model="queryParams.taskCode"
          placeholder="请输入任务编码/名称"
          clearable
          size="mini"
          @keyup.enter.native="handleQuery"
          @input="onInput()" />
        <!---->
      </el-form-item>
      <el-form-item label="事业部类型" prop="businessType">
        <el-select v-model="queryParams.businessType" size="mini" clearable filterable>
          <el-option
            v-for="item in statusOptionssmlj"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="物料类型" prop="materialType">
        <el-select
          v-model="queryParams.materialType"
          size="mini"
          clearable
          filterable
          @change="materialTypeChangeQuery">
          <el-option
            v-for="item in materialTypeOption"
            :key="item.signType"
            :label="item.signType"
            :value="item.signType" />
        </el-select>
      </el-form-item>
      <el-form-item label="物料名称" prop="materialName">
        <el-select
          v-model="queryParams.materialName"
          size="mini"
          clearable
          filterable
          @change="onInput()">
          <el-option
            v-for="item in materialNameOptionQuery"
            :key="item.signName"
            :label="item.signName"
            :value="item.signName" />
        </el-select>
      </el-form-item>
      <el-form-item label="物料状态" prop="status">
        <el-select
          v-model="queryParams.status"
          placeholder="请选择物料状态"
          clearable
          size="mini"
          @change="onInput()">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue" />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间" prop="createTime">
        <el-date-picker
          clearable
          size="mini"
          style="width: 200px"
          v-model="queryParams.createTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择创建时间"
          @change="onInput()">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
          >搜索
        </el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          >添加
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="toBeshippedM"
          @click="sendmaterFn"
          >整单发布
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="toBeshippedS"
          @click="handleDelete"
          >整单作废
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="el-icon-upload2" size="mini" @click="handleImport3"
          >批量导入
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="taskList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="任务编码" prop="taskCode" width="100" :show-overflow-tooltip="true" />
      <el-table-column label="任务名称" prop="taskName" width="230" :show-overflow-tooltip="true" />
      <el-table-column
        label="物料编码"
        prop="materialDataCode"
        width="150"
        :show-overflow-tooltip="true" />
      <el-table-column
        label="物料名称"
        prop="materialName"
        width="230"
        :show-overflow-tooltip="true" />
      <el-table-column
        label="物料类型"
        prop="materialType"
        width="90"
        :show-overflow-tooltip="true" />
      <el-table-column label="事业部类型" align="center" prop="businessType" width="90">
        <template slot-scope="scope">
          <dicts-tag :options="statusOptionssmlj" :value="scope.row.businessType" />
        </template>
      </el-table-column>

      <el-table-column label="任务状态" align="center" prop="status">
        <template slot-scope="scope">
          <dicts-tag :options="statusOptions" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="任务创建时间" align="center" prop="createTime" width="160" />
      <el-table-column label="任务发布时间" align="center" prop="issuingTime" width="120" />
      <el-table-column label="发放人" align="center" prop="issuer" />
      <el-table-column label="签收职位" align="center" prop="position" show-overflow-tooltip />
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        fixed="right"
        width="130">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status != 4"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >详情
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改物料签收任务中心对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rulesAdd" label-width="120px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="任务名称" prop="taskName">
              <el-input
                v-model="form.taskName"
                size="small"
                placeholder="请输入任务名称"
                @input="onInput"
                :disabled="form.status == '1'" />
            </el-form-item>
          </el-col>
          <!--<el-col :span="12" :class="title == '物料发放详情' ? 'qszw qszw-required' : 'qszw-required'">-->
          <!--<el-form-item label="选择职位" prop="positionValue">-->
          <!--<el-select v-model="positionValue" multiple collapse-tags placeholder="请选择" @change="positionValueChange" @remove-tag="removeTag">-->
          <!--<el-option label="全选" value="全选" @click.native="selectAllPosition" :disabled="positionValue.indexOf('全选') != -1 && title == '物料发放详情'"></el-option>-->
          <!--<el-option-->
          <!--v-for="item in positionOptions"-->
          <!--:key="item.dictLabel"-->
          <!--:label="item.dictLabel"-->
          <!--:value="item.dictLabel"-->
          <!--:disabled="positionValue.indexOf(item.dictLabel) != -1 && title == '物料发放详情'">-->
          <!--</el-option>-->
          <!--</el-select>-->
          <!--</el-form-item>-->
          <!--</el-col>-->
        </el-row>
        <el-row>
          <el-col :span="8">
            <el-form-item label="事业部" prop="businessType">
              <el-select
                v-model="form.businessType"
                size="small"
                clearable
                filterable
                @change="businessTypeFn"
                :disabled="form.status == '1'"
                style="width: 100%">
                <el-option
                  v-for="item in statusOptionssmlj"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="发放级别" prop="byType">
              <el-select
                v-model="form.byType"
                size="small"
                clearable
                filterable
                :disabled="form.status == '1'"
                style="width: 100%">
                <el-option
                  v-for="item in byTypeOption"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物料类型" prop="materialType">
              <el-select
                v-model="form.materialType"
                size="small"
                clearable
                filterable
                @change="materialTypeChange"
                :disabled="form.status == '1'"
                style="width: 100%">
                <el-option
                  v-for="item in materialTypeOption"
                  :key="item.signType"
                  :label="item.signType"
                  :value="item.signType" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="物料名称" prop="materialName">
              <!--              <el-input v-model="form.materialName" size="small" placeholder="请输入物料名称" @input="onInput"/> @change="onInput()"-->
              <el-select
                v-model="form.materialName"
                size="small"
                clearable
                filterable
                :disabled="form.status == '1'"
                @change="materialNameChange"
                style="width: 100%">
                <el-option
                  v-for="item in materialNameOption"
                  :key="item.signName"
                  :label="item.signName"
                  :value="item.signName" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row style="margin-bottom: 10px">
          <el-col :span="1" style="margin-right: 20px">
            <el-button type="primary" plain size="mini" @click="handleAddStore" v-if="nameIsSame"
              >添加
            </el-button>
          </el-col>
          <el-col :span="1" style="margin-right: 44px">
            <el-button type="primary" plain size="mini" @click="plHuifu" v-if="nameIsSame"
              >批量恢复
            </el-button>
          </el-col>
          <el-col :span="1">
            <el-button
              type="danger"
              plain
              size="mini"
              @click="plCancel"
              v-if="nameIsSame"
              :disabled="multipleAddStore"
              >批量作废
            </el-button>
          </el-col>
          <el-col :span="3" class="drfbrw">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="addStoreImport"
              v-if="nameIsSame"
              >导入发布任务
            </el-button>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-table
              class="tablenumClassName"
              :data="storeListAdd"
              :key="tablenum"
              ref="addStore"
              @selection-change="handleSelectionChangeStoreAdd"
              :row-class-name="rowHideFn">
              <el-table-column type="selection" width="55" align="center" :selectable="selected" />
              <el-table-column label="签发号" align="center" prop="issueNum" width="130" />
              <el-table-column
                label="发放到的库位名称"
                align="center"
                prop="receiveDeptname"
                width="130"
                :show-overflow-tooltip="true" />
              <el-table-column
                label="组织"
                align="center"
                prop="orgName"
                :show-overflow-tooltip="true" />
              <el-table-column
                label="签收人员名称"
                align="center"
                prop="receiveName"
                width="100"
                :show-overflow-tooltip="true" />
              <el-table-column label="签收人员工号" align="center" prop="receiveNum" width="100">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.receiveNum"
                    placeholder=""
                    size="mini"
                    style="width: 70px"
                    @change="
                      receiveNumInput(scope.$index, scope.row.receiveNum, scope.row.receiveDeptname)
                    "
                    :disabled="scope.row.isImport || isEdit">
                  </el-input>
                </template>
              </el-table-column>
              <el-table-column
                label="快递单号"
                align="center"
                prop="trackingNum"
                :show-overflow-tooltip="true" />
              <el-table-column label="发放数量" align="center" prop="issuingNum">
                <template slot-scope="scope">
                  <el-input
                    v-model="scope.row.issuingNum"
                    type="number"
                    placeholder=""
                    size="mini"
                    style="width: 70px"
                    @input="extendOnInput(scope.$index)"
                    :disabled="
                      !nameIsSame || scope.row.status == '3' || scope.row.status == '4'
                    "></el-input>
                </template>
              </el-table-column>
              <el-table-column label="物料状态" align="center" prop="status" width="100">
                <template slot-scope="scope">
                  <dicts-tag
                    :options="statusOptions2"
                    :value="
                      scope.row.status == null ? scope.row.status : scope.row.status.toString()
                    " />
                </template>
              </el-table-column>
              <el-table-column
                label="签发号发布时间"
                align="center"
                prop="issuingTime"
                width="120"
                :show-overflow-tooltip="true" />
              <!--              <el-table-column label="是否有效" align="center" prop="receiveShopPhone" />-->
              <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
                fixed="right"
                width="80">
                <template slot-scope="scope">
                  <el-button
                    type="text"
                    icon="el-icon-delete"
                    size="mini"
                    v-if="nameIsSame && scope.row.status != '4' && scope.row.status != '3'">
                    <span
                      v-if="scope.row.status == '1' || scope.row.status == '2'"
                      @click="handleDeleteStore(scope.row)"
                      style="display: inline-block; height: 100%"
                      >作废</span
                    >
                    <span v-if="scope.row.status == '0'" @click="handleDeleteTableItem(scope.row)"
                      >删除</span
                    >
                  </el-button>
                  <el-button
                    type="text"
                    icon="el-icon-refresh-right"
                    size="mini"
                    @click="handleReturnStore(scope.row)"
                    v-if="nameIsSame && scope.row.status == '4'">
                    <span>恢复</span>
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <div class="required line-ht36">物料图片上传：</div>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-upload
              ref="pictureUpload"
              :headers="upload.headers"
              :action="upload.url + '?updateSupport=' + upload.updateSupport"
              :disabled="form.status == '1'"
              list-type="picture-card"
              multiple
              accept="image/jpg,image/jpeg,image/png"
              :file-list="fileList"
              :before-upload="beforeImgUpload"
              :on-success="imgUploadSuccess"
              :on-error="imgUploadError">
              <i slot="default" class="el-icon-plus"></i>
              <div slot="file" slot-scope="{ file }">
                <img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
                <span class="el-upload-list__item-actions">
                  <span
                    class="el-upload-list__item-preview"
                    @click="handlePictureCardPreviewUpload(file)">
                    <i class="el-icon-zoom-in"></i>
                  </span>
                  <span
                    v-if="form.status != '1'"
                    class="el-upload-list__item-delete"
                    @click="handleRemoveUpload(file)">
                    <i class="el-icon-delete"></i>
                  </span>
                </span>
              </div>
            </el-upload>
            <el-dialog :visible.sync="dialogVisibleUpload" append-to-body>
              <img width="100%" :src="dialogImageUrlUpload" alt="" />
            </el-dialog>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer" v-if="nameIsSame">
        <el-button type="primary" @click="submitForm(1)">提 交</el-button>
        <el-button @click="submitForm(0)" :disabled="form.status == 1">暂 存</el-button>
      </div>
    </el-dialog>
    <el-dialog title="添加发布任务" :visible.sync="addTaskDialog.open" width="600px" append-to-body>
      <el-form ref="addTaskDialogForm" :model="addTaskDialog" label-width="80px">
        <el-form-item label="签发号">
          <el-input v-model="addTaskDialog.issueNum"></el-input>
        </el-form-item>
        <el-form-item label="组织" required>
          <el-input v-model="addTaskDialog.receiveDeptname"></el-input>
        </el-form-item>
        <el-form-item label="快递单号">
          <el-input v-model="addTaskDialog.trackingNum"></el-input>
        </el-form-item>
        <el-form-item label="发放数量" required>
          <el-input v-model="addTaskDialog.issuingNum"></el-input>
        </el-form-item>
        <el-form-item style="flex-direction: row; display: flex; justify-content: flex-end">
          <el-button type="primary" @click="onSubmitAddTask">添加</el-button>
          <el-button @click="addTaskDialog.open = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="添加任务" :visible.sync="storeOpen" width="80%" append-to-body>
      <el-form
        ref="addStoreForm"
        :model="addStoreForm"
        :inline="true"
        size="mini"
        v-show="showSearchStore"
        label-width="130px">
        <!--<el-form-item label="门店编码" prop="shopcode">-->
        <!--<el-input v-model="addStoreForm.shopcode" clearable placeholder="请输入门店编码" @input="onInput()" />-->
        <!--</el-form-item>-->
        <el-form-item label="发放到的库位名称" prop="receiveName">
          <el-input
            v-model="addStoreForm.receiveName"
            clearable
            placeholder="请输入发放到的库位名称"
            @input="onInput()" />
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="storeQuery"
            >搜索
          </el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQueryStore">重置</el-button>
        </el-form-item>
      </el-form>
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="primary"
            plain
            icon="el-icon-plus"
            size="mini"
            :disabled="multipleStore"
            @click="addStore"
            >批量添加
          </el-button>
        </el-col>
        <right-toolbar :showSearch.sync="showSearchStore" @queryTable="storeQuery"></right-toolbar>
      </el-row>
      <el-table
        v-loading="loadingStore"
        :data="storeList"
        @selection-change="handleSelectionChangeStore">
        <el-table-column type="selection" width="55" align="center" />
        <!--      <el-table-column label="任务id" align="center" prop="taskId" />-->
        <el-table-column label="库位名称" prop="receiveName" :show-overflow-tooltip="true" />
        <el-table-column label="库位编码" align="center" prop="receiveCode" width="110" />
        <!--<el-table-column label="门店电话" align="center" prop="receiveShopPhone"/>-->
        <!--<el-table-column label="门店地址" align="center" prop="receiveShopAddress" :show-overflow-tooltip="true"/>-->
        <el-table-column
          label="操作"
          align="center"
          class-name="small-padding fixed-width"
          width="100">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-plus" @click="addStore(scope.row)"
              >添加
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="totalStore > 0"
        :total="totalStore"
        :page.sync="addStoreForm.pageNum"
        :limit.sync="addStoreForm.pageSize"
        @pagination="getStoreList" />
    </el-dialog>
    <el-dialog
      class="upload"
      :title="upload2.title"
      :visible.sync="upload2.open"
      width="400px"
      append-to-body>
      <div style="margin-bottom: 14px">
        <el-link type="primary" style="font-size: 14px" @click="importTemplate">下载模板</el-link>
      </div>

      <el-upload
        ref="upload2"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload2.headers"
        :action="upload2.url + '?updateSupport=' + upload2.updateSupport"
        :disabled="upload2.isUploading"
        :on-progress="handleFileUploadProgress"
        :on-success="handleFileSuccess"
        :auto-upload="false"
        drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">
          将文件拖到此处，或
          <em>点击上传</em>
        </div>

        <div class="el-upload__tip" style="color: red" slot="tip">
          提示：仅允许导入“xls”或“xlsx”格式文件！
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm" :disabled="upload2.isUploading"
          >确 定
        </el-button>
        <el-button @click="upload2.open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!--任务列表数据导入-->
    <el-dialog :title="upload3.title" :visible.sync="upload3.open" width="400px" append-to-body>
      <el-upload
        ref="upload3"
        :limit="1"
        accept=".xlsx, .xls"
        :headers="upload3.headers"
        :action="upload3.url + '?updateSupport=' + upload3.updateSupport"
        :disabled="upload3.isUploading"
        :on-progress="handleFileUploadProgress3"
        :on-success="handleFileSuccess3"
        :auto-upload="false"
        drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <span>仅允许导入xls、xlsx格式文件。</span>
          <el-link
            type="primary"
            :underline="false"
            style="font-size: 12px; vertical-align: baseline"
            @click="importTemplate3"
            >下载模板</el-link
          >
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm3">确 定</el-button>
        <el-button @click="upload3.open = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTask,
  getTask,
  voidmater,
  addTask,
  updateTask,
  listStore,
  addtaskcancel,
  sendmater,
  delSign,
  importSignUser,
  returnStore,
  importTemplate,
  selectOrganization,
  plcancel,
  plhuifu,
  getNameByCode,
  getDictByType,
  importData,
  getDictTask,
} from '@/api/sfa/taskuser'
import { getToken } from '@/utils/auth'
import { listDictype } from '@/api/sfa/dictype'

export default {
  name: 'TaskUser',
  components: {},
  data() {
    return {
      positionOptions: [],
      positionValue: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      toBeshippedS: true,
      toBeshippedM: true,

      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料签收任务中心表格数据
      taskList: [],
      updateTaskCode: '',
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      statusOptions: [],
      statusOptions2: [],
      // 表单参数
      form: {
        byType: '',
        materialName: '',
      },
      // 表单校验
      rules: {},
      dialogImageUrlUpload: '',
      dialogVisibleUpload: false,
      disabledUpload: false,
      storeOpen: false,
      downLoadForm: {},
      addStoreForm: {
        pageNum: 1,
        pageSize: 10,
      },
      showSearchStore: true,
      multipleStore: true,
      loadingStore: true,
      storeList: [],
      storeListAdd: [],
      totalStore: 0,
      storeCodes: [],
      storeSelect: [],
      rulesAdd: {
        taskName: [{ required: true, message: '请输入任务名称', trigger: 'blur' }],
        materialType: [{ required: true, message: '请输入物料类型', trigger: 'change' }],
        businessType: [{ required: true, message: '请选择事业部', trigger: 'change' }],
        materialName: [{ required: true, message: '请输入物料名称', trigger: 'change' }],
        byType: [{ required: true, message: '请选择发放级别', trigger: 'change' }],
      },
      fileList: [],
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/common/uploadAliyun',
        loadProgress: 10,
      },
      upload2: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/common/upload',
        loadProgress: 10,
      },
      upload3: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: '',
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/guide/taskuser/importData',
      },
      addTaskDialog: {
        open: false,
      },
      canelIds: [],
      canelShopCodes: [],
      multipleAddStore: true,
      addStoreForm2: {},
      storeListAddSubmit: [],
      tablenum: 0,
      upladLoading: null,
      name: '',
      formCreatBy: '',
      nameIsSame: true,
      materialNameOptionQuery: [],
      materialNameOption: [],
      statusOptionssmlj: [],
      materialTypeOption: [],
      businessType: [],

      selection: [],
      cancelItems: [],
      currentRow: '',
      byTypeOption: [], //发放级别
      isEdit: false, //接收编号是否可编辑
    }
  },
  watch: {
    'form.byType': {
      handler(newVal, oldVal) {
        // 切换发放级别需要清口添加的数据
        this.storeListAdd = []
        // newVal == 4 时为销售人员，员工编号禁止数据，
        if (newVal == 4) {
          this.isEdit = true
        } else {
          this.isEdit = false
        }
        console.log(newVal, oldVal)
      },
      immediate: true,
    },
    'form.materialName': {
      handler(newVal, oldVal) {
        if (this.title !== '物料发放添加') return
        const material = this.materialNameOption.find((item) => item.signName == newVal)
        if (newVal && material.signPicture) {
          const imgFile = {
            url: material.signPicture,
            id: material.id,
            name: material.signName,
            response: {
              url: material.signPicture,
              fileName: material.signName,
            },
          }
          this.fileList = [imgFile]
        } else {
          this.fileList = []
        }
      },
    },
  },
  created() {
    this.getDicts('task_status').then((response) => {
      this.statusOptions = response.data
    })
    this.getDicts('sign_status').then((response) => {
      this.statusOptions2 = response.data
    })
    this.getDicts('sign_position').then((response) => {
      this.positionOptions = response.data
    })
    this.getDictTask()

    // this.getMaterialNameOptionAll();
    this.getMaterialTypeOption()
    this.name = this.$store.state.user.name
    this.getList()
  },
  methods: {
    getDictTask() {
      getDictTask('BU_type').then((response) => {
        this.statusOptionssmlj = response.data
      })
    },
    onInput() {
      this.$forceUpdate()
    },
    businessTypeFn(val) {
      this.$forceUpdate()
      this.storeListAdd = []
      this.getDictByTypeFun()
    },
    extendOnInput(index) {
      // this.storeListAdd[index].extend = this.storeListAdd[index].extend.replace(/[^\d.]/g,'');
      this.storeListAdd[index].extend = /^[0-9]*$/.test(parseInt(this.storeListAdd[index].extend))
        ? String(parseInt(this.storeListAdd[index].extend)).replace('.', '')
        : ''
      this.$forceUpdate()
    },
    receiveNumInput(index, code, Deptname) {
      getNameByCode(code).then((res) => {
        if (res.code == 200 && res.data) {
          let sameArr = []
          // this.storeListAdd[index].receiveName = res.data.nick_name;
          // this.storeListAdd[index].orgName = res.data.orgName;
          this.storeListAdd.forEach((storeListAddItem, storeListAddIndex) => {
            if (
              storeListAddItem.receiveNum == code &&
              storeListAddItem.receiveDeptname == Deptname &&
              index != storeListAddIndex
            ) {
              this.storeListAdd[index].receiveNum = ''
              this.storeListAdd[index].receiveName = ''
              this.storeListAdd[index].orgName = ''
              sameArr.push(storeListAddIndex)
            }
          })
          if (sameArr.length == 0) {
            this.storeListAdd[index].receiveName = res.data.nick_name
            this.storeListAdd[index].orgName = res.data.orgName
          }
          this.tablenum++
          this.$forceUpdate()
        } else {
          this.storeListAdd[index].receiveName = ''
          this.storeListAdd[index].receiveNum = ''
          this.storeListAdd[index].orgName = ''
          this.tablenum++
          this.$forceUpdate()
        }
      })
    },
    selectAllPosition() {
      if (this.positionValue.length < this.positionOptions.length) {
        this.positionValue = []
        this.positionOptions.map((item) => {
          this.positionValue.push(item.dictLabel)
        })
        this.positionValue.unshift('全选')
      } else {
        if (this.title != '物料发放详情') {
          this.positionValue = []
        }
      }
    },
    positionValueChange(val) {
      if (!val.includes('全选') && val.length == this.positionOptions.length) {
        this.positionValue.unshift('全选')
      } else if (val.includes('全选') && val.length - 1 < this.positionOptions.length) {
        this.positionValue = this.positionValue.filter((item) => {
          return item != '全选'
        })
      }
    },
    removeTag(val) {
      if (val == '全选') {
        this.positionValue = []
      }
    },
    // getMaterialNameOptionAll(){
    //     let obj = {
    //         type:1,
    //     };
    //     this.getMaterialNameOption(obj,'materialNameOptionAll');
    // },
    getMaterialTypeOption() {
      let obj = {
        type: 0,
      }
      this.getMaterialNameOption(obj, 'materialTypeOption')
    },
    getMaterialNameOption(obj, str) {
      let that = this
      listDictype(obj).then((response) => {
        if (str == 'materialNameOptionAll') {
          that.materialNameOptionAll = response.rows
        } else if (str == 'materialTypeOption') {
          that.materialTypeOption = response.rows
        } else if (str == 'materialNameOption') {
          that.materialNameOption = response.rows
        } else if (str == 'materialNameOptionQuery') {
          that.materialNameOptionQuery = response.rows
        }
      })
    },
    materialTypeChangeQuery(val) {
      this.queryParams.materialName = ''
      if (val != '' && val != null) {
        let pid
        this.materialTypeOption.forEach((item) => {
          if (item.signType == val) {
            pid = item.id
            let obj = {
              type: 1,
              pid,
            }
            this.getMaterialNameOption(obj, 'materialNameOptionQuery')
          }
        })
      } else {
        this.materialNameOptionQuery = []
      }
      this.$forceUpdate()
    },
    materialTypeChange(val, isUplate) {
      this.$forceUpdate()
      if (!isUplate) {
        this.form.materialName = ''
      }

      if (val != '' && val != null) {
        let pid
        this.materialTypeOption.forEach((item) => {
          if (item.signType == val) {
            pid = item.id
            let obj = {
              type: 1,
              pid,
            }
            this.getMaterialNameOption(obj, 'materialNameOption')
          }
        })
      } else {
        this.materialNameOption = []
      }
    },
    statusFormat(row) {
      return this.selectDictLabel(this.statusOptions, row.status)
    },
    statusFormat2(row) {
      return this.selectDictLabel(this.statusOptions2, row.status)
    },
    /** 查询物料签收任务中心列表 */
    getList() {
      this.loading = true
      listTask(this.queryParams).then((response) => {
        this.taskList = response.rows
        this.total = response.total
        this.loading = false
      })
    },

    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        materialType: undefined,
        taskName: undefined,
        businessType: undefined,
        materialName: undefined,
      }
      this.formCreatBy = ''
      this.resetForm('form')
      this.fileList = []
      this.storeListAdd = []
      this.positionValue = []
      this.materialNameOption = []
      if (this.$refs.pictureUpload && this.$refs.pictureUpload.uploadFiles) {
        this.$refs.pictureUpload.uploadFiles = []
      }
      this.addStoreForm2.shopInfo = ''
      this.addStoreForm2.status = ''
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.queryParams.ffsj = ''
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      // this.ids = selection.map(item => item.id);
      this.ids = []
      this.single = selection.length !== 1
      this.multiple = !selection.length
      // let status = selection.map(item => item.status);
      let status = [],
        creatByIsSame = []
      selection.forEach((item, index) => {
        status.push(item.status)
        this.ids.push(item.id)
        item.createBy == this.name ? creatByIsSame.push(true) : creatByIsSame.push(false)
      })
      if (!this.multiple) {
        if (status.indexOf('1') != -1 || creatByIsSame.indexOf(false) != -1) {
          this.toBeshippedM = true
        } else {
          this.toBeshippedM = false
        }
      } else {
        this.toBeshippedM = true
      }
      if (!this.multiple) {
        if (creatByIsSame.indexOf(false) != -1) {
          this.toBeshippedS = true
        } else {
          this.toBeshippedS = false
        }
      } else {
        this.toBeshippedS = true
      }
    },
    selected(row, index) {
      if (row.statue == '3') {
        return false //不可勾选
      } else {
        return true //可勾选
      }
    },
    handleSelectionChangeStoreAdd(selection) {
      this.cancelItems = selection
      this.canelIds = selection.map((item) => item.id)
      this.canelShopCodes = selection.map((item) => item.receiveShopCode)
      let multiple = !selection.length
      let status = selection.map((item) => item.status)
      if (!multiple) {
        if (status.indexOf(3) != -1 || status.indexOf(2) != -1) {
          this.multipleAddStore = true
        } else {
          this.multipleAddStore = false
        }
      } else {
        this.multipleAddStore = true
      }
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.updateTaskCode = ''
      this.open = true
      this.title = '物料发放添加'
      this.nameIsSame = true
    },
    getDictByTypeFun(callback) {
      this.byTypeOption = []
      if (this.form.businessType == '') {
        this.form.byType = ''
        return
      }
      getDictByType({ BUType: this.form.businessType }).then((res) => {
        if (res.code == 200) {
          this.byTypeOption = res.data
          callback && callback()
          // this.form.byType = this.byTypeOption.length ? this.byTypeOption[0].dictValue : "";
        }
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.currentRow = row
      this.reset()
      const id = row.id || this.ids.join(',')
      getTask({ id }).then((response) => {
        this.form.taskName = response.data.guideMaterialTask.taskName
        this.form.materialType = response.data.guideMaterialTask.materialType
        this.form.businessType = response.data.guideMaterialTask.businessType
        this.form.materialName = response.data.guideMaterialTask.materialName
        // this.positionValue = response.data.guideMaterialTask.position.split(',');
        this.form.id = response.data.guideMaterialTask.id
        this.updateTaskCode = response.data.guideMaterialTask.taskCode
        this.form.status = response.data.guideMaterialTask.status

        this.form.fileurl = this.fileList.map((item) => item.url).join(',')
        this.formCreatBy = response.data.guideMaterialTask.createBy
        this.formCreatBy == this.name ? (this.nameIsSame = true) : (this.nameIsSame = false)
        this.materialTypeChange(this.form.materialType, 'isUplate')
        // if (this.positionValue.length == this.positionOptions.length){
        //   this.positionValue.unshift("全选");
        // }
        this.open = true
        this.title = '物料发放详情'
        // 获取发放级别
        this.getDictByTypeFun(() => {
          this.$set(this.form, 'byType', response.data.guideMaterialTask.level)
          this.$nextTick(() => {
            this.storeListAdd = response.data.materialSigns
            this.fileList = this.fileListsrcFn(response.data.grantimginfo)
          })
          // this.form.byType = response.data.guideMaterialTask.level;
        })
      })
    },
    fileListsrcFn(arr) {
      let list = []
      arr.forEach((item, index) => {
        let obj = {
          response: {
            url: item.path,
          },
          url: item.path,
        }
        list.push(obj)
      })
      return list
    },
    /** 提交按钮 */
    submitForm(val) {
      let that = this
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.storeListAdd.length <= 0) {
            this.$modal.msgError('请选择发放门店')
            return
          } else {
            let arr = [],
              arr1 = []
            this.storeListAdd.forEach((item) => {
              if (item.issuingNum == '' || item.issuingNum == null) {
                arr.push(true)
              }
              if (item.receiveName == '' || item.issuingNum == null) {
                arr1.push(true)
              }
            })
            if (arr.length > 0) {
              this.$modal.msgError('发放数量不能为空')
              return
            }
            if (arr1.length > 0) {
              this.$modal.msgError('员工姓名不能为空')
              return
            }
          }
          if (this.fileList.length <= 0) {
            this.$modal.msgError('请上传物料图片')
            return
          }
          // let subPostionValue = this.positionValue.filter((item)=>{
          //   return item != '全选'
          // })
          // this.form.position = subPostionValue.join(',');
          setTimeout(function () {
            that.form.data = JSON.stringify(that.storeListAdd)
            that.form.status = val
            that.form.level = that.form.byType
            that.form.fileurl = that.fileList.map((item) => item.response.url).join(',')
            if (that.form.id != null) {
              updateTask(that.form).then((response) => {
                that.$modal.msgSuccess('修改成功')
                that.open = false
                that.getList()
              })
            } else {
              addTask(that.form).then((response) => {
                that.$modal.msgSuccess('新增成功')
                that.open = false
                that.getList()
              })
            }
          }, 500)
        }
      })
    },
    // 批量发货
    sendmaterFn() {
      const id = this.ids.join(',')
      this.$confirm('是否确认批量发货已选中数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return sendmater({ id })
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('发货成功')
        })
        .catch(() => {})
    },
    /** 删除按钮操作 */
    handleDeleteTableItem(row) {
      let that = this
      this.$confirm('是否确认删除数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          that.storeListAdd = that.storeListAdd.filter((item) => item != row)
          that.tablenum++
          this.$forceUpdate()
        })
        .then(() => {})
        .catch(() => {})
    },
    /** 作废按钮操作 */
    handleDelete(row) {
      const id = row.id || this.ids.join(',')
      this.$confirm('是否确认作废已选中数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          return voidmater({ id })
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('作废成功')
        })
        .catch(() => {})
    },
    handleRemoveUpload(file) {
      let uploadFiles = this.$refs.pictureUpload.uploadFiles
      for (var i = 0; i < uploadFiles.length; i++) {
        if (uploadFiles[i]['url'] == file.url) {
          uploadFiles.splice(i, 1)
          this.fileList.splice(i, 1)
        }
      }
    },
    handlePictureCardPreviewUpload(file) {
      this.dialogImageUrlUpload = file.url
      this.dialogVisibleUpload = true
    },
    beforeImgUpload(file) {
      var img = file.name.substring(file.name.lastIndexOf('.') + 1)
      const suffix = img === 'jpg'
      const suffix2 = img === 'png'
      const suffix3 = img === 'jpeg'
      // const isLt1M = file.size / 1024 / 1024 < 1;
      if (!suffix && !suffix2 && !suffix3) {
        this.$message.error('只能上传图片！')
        return false
      }
      // 可以限制图片的大小
      // if (!isLt1M) {
      //     this.$message.error('上传图片大小不能超过 1MB!');
      // }
      return suffix || suffix2 || suffix3
    },
    imgUploadSuccess(response, file, fileList) {
      this.fileList = fileList
    },
    imgUploadError(err, file, fileList) {
      this.$message.error('上传失败，请重新上传！')
    },
    getStoreList() {
      this.loadingStore = true
      // var deptLevel = 1;
      // if (this.form.businessType == "DIY" || this.form.businessType == "GZ") {
      //   deptLevel = 3;
      // }
      this.addStoreForm.level = this.form.byType
      this.addStoreForm.BUType = this.form.businessType
      selectOrganization(this.addStoreForm).then((response) => {
        this.storeList = response.data
        this.totalStore = response.total
        this.loadingStore = false
      })
      // let obj = {
      //   pageNum: 1,
      //   pageSize: 10,
      //   receiveDeptname:this.addStoreForm.shopname,
      //   position:this.positionValue.join(',')
      // }
      // selectOrganization(obj).then(response => {
      //     this.storeList = response.rows;
      //     this.totalStore = response.total;
      //     this.loadingStore = false;
      //   });
    },
    handleAddTask() {
      // if (this.positionValue.length == 0) {
      //   this.$message({
      //     type: 'error',
      //     message: '请先选择职位!'
      //   });
      // }else {
      //   this.addTaskDialog.open = true;
      // }
      this.addTaskDialog.open = true
    },
    onSubmitAddTask() {
      let that = this
      if (
        that.addTaskDialog.receiveDeptname == undefined ||
        that.addTaskDialog.receiveDeptname == '' ||
        that.addTaskDialog.receiveDeptname == null
      ) {
        this.$message({
          type: 'error',
          message: '请输入组织名称',
        })
        return
      }
      if (
        that.addTaskDialog.issuingNum == undefined ||
        that.addTaskDialog.issuingNum == '' ||
        that.addTaskDialog.issuingNum == null
      ) {
        this.$message({
          type: 'error',
          message: '请输入发放数量',
        })
        return
      }
    },
    handleAddStore() {
      // if (this.positionValue.length == 0) {
      //   this.$message({
      //     type: 'error',
      //     message: '请先选择职位!'
      //   });
      // }else {
      //   this.storeOpen = true;
      //   this.addStoreForm.position = this.positionValue.join(',');
      //   this.getStoreList();
      // }
      if (
        this.form.businessType == undefined ||
        this.form.businessType == null ||
        this.form.businessType == ''
      ) {
        this.$modal.msgWarning('请选择事业部！')
        return
      }
      if (this.form.byType == undefined || this.form.byType == null || this.form.byType == '') {
        this.$modal.msgWarning('请选择发放级别！')
        return
      }
      this.storeOpen = true
      // this.addStoreForm.position = this.positionValue.join(',');
      this.getStoreList()
    },
    plHuifu() {
      let that = this
      let ids = []
      let isCancel = true
      that.cancelItems.forEach((item) => {
        ids.push(item.id)
        if (item.status != '4') {
          isCancel = false
        }
      })
      if (isCancel == true) {
        this.$confirm('是否确认操作已选中数据?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(function () {
            plhuifu(ids).then((res) => {
              if (res.code == 200) {
                that.$message({
                  type: 'success',
                  message: '批量恢复成功',
                })
                that.handleUpdate(that.currentRow)
              }
            })
          })
          .then(() => {})
          .catch(() => {})
      } else {
        this.$message({
          type: 'error',
          message: '请选择已作废的任务',
        })
      }
    },
    plCancel() {
      let that = this
      let ids = []
      let isCancel = true
      that.cancelItems.forEach((item) => {
        ids.push(item.id)
        if (item.status == '0' || item.status == '4') {
          isCancel = false
        }
      })
      if (isCancel == true) {
        this.$confirm('是否确认操作已选中数据?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(function () {
            plcancel(ids).then((res) => {
              if (res.code == 200) {
                that.$message({
                  type: 'success',
                  message: '批量作废成功',
                })
                that.handleUpdate(that.currentRow)
              }
            })
          })
          .then(() => {})
          .catch(() => {})
      } else {
        this.$message({
          type: 'error',
          message: '未发布和已作废的任务不能作废',
        })
      }
    },
    handleDeleteStore(row) {
      let that = this
      this.$confirm('是否确认操作已选中数据?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(function () {
          that.delFn(row)
        })
        .then(() => {})
        .catch(() => {})
    },
    delFn(row) {
      let id = '',
        idArr = [],
        shopCodes = [],
        storeListAdd = [...this.storeListAdd]
      if (row.id || row.id === 0) {
        id = row.id
        idArr.push(row.id)
        shopCodes.push(row.receiveShopCode)
      } else {
        id = this.canelIds.join(',')
        idArr = this.canelIds
        shopCodes = this.canelShopCodes
      }
      let indexArr = []
      this.canelIds.forEach((id, a) => {
        if (id == -1) {
          indexArr.push(a)
        }
      })
      if (this.form.id) {
        if (id == -1) {
          this.storeListAdd.forEach((item, index) => {
            shopCodes.forEach((data, i) => {
              if (item.receiveShopCode == data) {
                this.storeListAdd.splice(index, 1)
              }
            })
          })
        } else if (indexArr.length > 0) {
          storeListAdd.forEach((store, i) => {
            indexArr.forEach((c, id) => {
              if (store.receiveShopCode == shopCodes[c] && store.id == -1) {
                this.storeListAdd.forEach((vv, ii) => {
                  if (vv.receiveShopCode == store.receiveShopCode) {
                    this.storeListAdd.splice(ii, 1)
                  }
                })
              }
            })
          })
          // for (let ic = this.storeListAdd.length - 1; ic >= 0; ic--) {
          //     indexArr.forEach((c,id)=>{
          //         if (this.storeListAdd[ic].receiveShopCode == shopCodes[c] && this.storeListAdd[ic].id == -1) {
          //             this.storeListAdd.splice(ic, 1);
          //         }
          //     })
          // }
          indexArr.sort(function (a, b) {
            return b - a
          })

          indexArr.forEach((data, i) => {
            idArr.splice(data, 1)
          })

          if (idArr.length > 0) {
            if (this.form.status == 1) {
              addtaskcancel({ id: idArr.join(',') }).then((response) => {
                // this.handleUpdate(this.form);
                this.storeListAdd.forEach((item, index) => {
                  idArr.forEach((data, i) => {
                    if (item.id == data) {
                      this.storeListAdd[index].status = 4
                      this.$forceUpdate()
                    }
                  })
                })
                this.$refs.addStore.clearSelection()
              })
            } else {
              // delSign(idArr).then(response => {
              //     for (let ia = this.storeListAdd.length - 1; ia >= 0; ia--) {
              //         idArr.forEach((b,ib)=>{
              //             if (this.storeListAdd[ia].id == b) {
              //                 this.storeListAdd.splice(ia, 1);
              //             }
              //         })
              //     }
              // });
              storeListAdd.forEach((store, i) => {
                idArr.forEach((id, iid) => {
                  if (store.id == id) {
                    this.storeListAdd.forEach((vv, ii) => {
                      if (vv.id == store.id) {
                        this.storeListAdd.splice(ii, 1)
                      }
                    })
                  }
                })
              })
            }
          }
        } else {
          if (this.form.status == 1) {
            addtaskcancel({ id }).then((response) => {
              // this.handleUpdate(this.form);
              this.storeListAdd.forEach((item, index) => {
                idArr.forEach((data, i) => {
                  if (item.id == data) {
                    this.storeListAdd[index].status = 4
                    this.$forceUpdate()
                  }
                })
              })
              this.$refs.addStore.clearSelection()
            })
          } else {
            // delSign(idArr).then(response => {
            //     for (let i = this.storeListAdd.length - 1; i >= 0; i--) {
            //         idArr.forEach((a,id)=>{
            //             if (this.storeListAdd[i].id == a) {
            //                 this.storeListAdd.splice(i, 1);
            //             }
            //         })
            //     }
            // });
            storeListAdd.forEach((store, i) => {
              idArr.forEach((id, iid) => {
                if (store.id == id) {
                  this.storeListAdd.forEach((vv, ii) => {
                    if (vv.id == store.id) {
                      this.storeListAdd.splice(ii, 1)
                    }
                  })
                }
              })
            })
          }
        }
      } else {
        storeListAdd.forEach((store, i) => {
          shopCodes.forEach((data, is) => {
            if (store.receiveShopCode == data && store.id == -1) {
              this.storeListAdd.forEach((vv, ii) => {
                if (vv.receiveShopCode == store.receiveShopCode) {
                  this.storeListAdd.splice(ii, 1)
                }
              })
            }
          })
        })
        // for(let b = 0; b < this.storeListAdd.length; b++) {
        //     shopCodes.forEach((data,i)=>{
        //         if(this.storeListAdd[b] && this.storeListAdd[b].receiveShopCode == data && this.storeListAdd[b].id == -1){
        //             this.storeListAdd.splice(b,1);
        //             b--;
        //         }
        //     })
        // }
      }
    },
    // 恢复门店
    handleReturnStore(row) {
      let id = row.id
      returnStore({ id }).then((response) => {
        // this.handleUpdate(this.form);
        // this.storeListAdd.forEach((item, index) => {
        //     if(item.id == id){
        //         this.storeListAdd[index].status = '1';
        //     }
        // })
        this.handleUpdate(this.currentRow)
      })
    },
    storeQuery() {
      this.addStoreForm.pageNum = 1
      this.getStoreList()
    },
    resetQueryStore() {
      this.addStoreForm.shopcode = ''
      this.addStoreForm.shopname = ''
      this.addStoreForm.pageNum = 1
      this.resetForm('addStoreForm')
      this.storeQuery()
    },
    addStore(row) {
      let that = this
      debugger
      if (row.receiveName == undefined) {
        if (that.storeListAdd.length == 0) {
          that.selection.forEach((resItem, resIndex) => {
            resItem.status = '0'
          })
          that.storeListAdd = that.selection
        } else {
          that.selection.forEach((resItem, resIndex) => {
            resItem.status = '0'
            //     that.storeListAdd.forEach((storeItem,storeIndex)=>{
            //       if(resItem.receiveDeptname == storeItem.receiveDeptname){
            //     that.storeListAdd[storeIndex] = resItem
            //   }
            // })
            that.storeListAdd.push(resItem)
          })
        }
        // let storeListAdd = [...that.storeListAdd,...that.selection];
        const resAdd = new Map()
        // that.storeListAdd = storeListAdd.filter((item)=> !resAdd.has(item.receiveDeptname) && resAdd.set(item.receiveDeptname,1));
        that.storeListAdd.forEach((resItem, resIndex) => {
          // 当选择是销售员时 receiveName，receiveCode 代表时销售员名称和编号；反之则代表的是费用归属方(单位名称)和编码，此时需要输入领取人的编号查询领取人名称
          // 如果当前选中的 发放级别是"销售员"，不需要获取领取人，当前员工就是领取人，自动赋值员工编号并禁止输入，费用归属也是当前员工
          // 如果不是销售员 receiveName 字段表示是费用归属(receiveDeptname); receiveName 清空可并根据员工编号查询员工姓名
          // isEdit：true 为销售人员，不可编辑
          if (this.isEdit) {
            resItem.receiveNum = resItem.receiveNum || resItem.receiveCode
            resItem.receiveDeptcode = resItem.receiveDeptcode || resItem.receiveCode
            resItem.receiveDeptname = resItem.receiveDeptname || resItem.receiveName
          } else {
            //添加操作返回的字段为 receiveCode和receiveName，每次添加都需要赋值
            if (resItem.receiveDeptname == undefined || resItem.receiveDeptname == '') {
              resItem.receiveDeptname = resItem.receiveName
              resItem.receiveDeptcode = resItem.receiveCode
              resItem.receiveName = ''
            } else {
              resItem.receiveDeptname = resItem.receiveDeptname
            }
          }
          if (resItem.isImport == undefined) {
            resItem.isImport = false
          }
          if (resItem.issueNum == undefined || resItem.issueNum == null || resItem.issueNum == '') {
            let randomCode = ''
            if (resIndex + 1 < 10) randomCode = '000' + (resIndex + 1)
            if (resIndex + 1 >= 10 && resIndex + 1 < 100) randomCode = '00' + (resIndex + 1)
            if (resIndex + 1 >= 100 && resIndex + 1 < 1000) randomCode = '0' + (resIndex + 1)
            if (resIndex + 1 >= 1000) randomCode = '' + (resIndex + 1)
            resItem.issueNum = that.updateTaskCode + randomCode
          }
        })
        this.tablenum++
        this.$forceUpdate()
        this.storeOpen = false
      } else {
        row.status = '0'
        // if (that.storeListAdd.length == 0){
        //   that.storeListAdd.push(row);
        // } else {
        //   that.storeListAdd.forEach((item,index)=>{
        //     if(item.receiveDeptname == row.receiveDeptname){
        //     that.storeListAdd[index] = row;
        //   }
        //   that.storeListAdd.push(row);
        //   const resAdd = new Map();
        //   that.storeListAdd = that.storeListAdd.filter((item)=> !resAdd.has(item.receiveDeptname) && resAdd.set(item.receiveDeptname,1));
        // })
        // }
        that.storeListAdd.push(row)
        that.storeListAdd.forEach((resItem, resIndex) => {
          if (this.isEdit) {
            resItem.receiveNum = resItem.receiveNum || resItem.receiveCode
            resItem.receiveDeptcode = resItem.receiveDeptcode || resItem.receiveCode
            resItem.receiveDeptname = resItem.receiveDeptname || resItem.receiveName
          } else {
            if (resItem.receiveDeptname == undefined || resItem.receiveDeptname == '') {
              resItem.receiveDeptname = resItem.receiveName
              resItem.receiveDeptcode = resItem.receiveCode
              resItem.receiveName = ''
            } else {
              resItem.receiveDeptname = resItem.receiveDeptname
            }
          }
          if (resItem.issueNum == undefined || resItem.issueNum == null || resItem.issueNum == '') {
            let randomCode = ''
            if (resIndex + 1 < 10) randomCode = '000' + (resIndex + 1)
            if (resIndex + 1 >= 10 && resIndex + 1 < 100) randomCode = '00' + (resIndex + 1)
            if (resIndex + 1 >= 100 && resIndex + 1 < 1000) randomCode = '0' + (resIndex + 1)
            if (resIndex + 1 >= 1000) randomCode = '' + (resIndex + 1)
            resItem.issueNum = that.updateTaskCode + randomCode
          }
        })
        this.tablenum++
        this.$forceUpdate()
        this.storeOpen = false
      }
    },
    handleSelectionChangeStore(selection) {
      this.storeCodes = selection.map((item) => item.receiveShopCode)
      this.selection = selection
      this.storeSelect = selection
      this.multipleStore = !selection.length
    },
    toRecord(row) {
      this.$router.push({
        path: '/sign/sign',
        query: { taskId: row.id, extend: row.extend, name: row.createBy },
      })
    },
    addStoreQuery() {
      // this.storeListAddSubmit = this.storeListAdd;
      this.storeListAdd.forEach((item, index) => {
        if (
          (this.addStoreForm2.shopInfo == '' && this.addStoreForm2.status == '') ||
          (this.addStoreForm2.shopInfo != '' &&
            this.addStoreForm2.status == '' &&
            (item.receiveShopCode.indexOf(this.addStoreForm2.shopInfo) != -1 ||
              item.receiveShopName.indexOf(this.addStoreForm2.shopInfo) != -1)) ||
          (this.addStoreForm2.status != '' &&
            this.addStoreForm2.shopInfo == '' &&
            item.status.toString() == this.addStoreForm2.status) ||
          (this.addStoreForm2.status != '' &&
            this.addStoreForm2.shopInfo != '' &&
            item.status.toString() == this.addStoreForm2.status &&
            (item.receiveShopCode.indexOf(this.addStoreForm2.shopInfo) != -1 ||
              item.receiveShopName.indexOf(this.addStoreForm2.shopInfo) != -1))
        ) {
          item.isHide = false
        } else {
          item.isHide = true
        }
      })
      this.tablenum++
      this.$forceUpdate()
    },
    resetAddStoreQuery() {
      this.addStoreForm2.shopInfo = ''
      this.addStoreForm2.status = ''
      this.resetForm('addStoreForm2')
      this.addStoreQuery()
    },
    rowHideFn({ row, rowIndex }) {
      if (row.isHide == true) {
        return 'hideRow'
      } else {
        return
      }
    },
    addStoreImport() {
      if (
        this.form.businessType == undefined ||
        this.form.businessType == null ||
        this.form.businessType == ''
      ) {
        this.$modal.msgWarning('请选择事业部！')
        return
      }
      if (this.form.byType == undefined || this.form.byType == null || this.form.byType == '') {
        this.$modal.msgWarning('请选择发放级别！')
        return
      }
      this.upload2.title = '物料签收导入'
      this.upload2.open = true
    },
    handleFileBefore(file) {
      if (this.positionValue.length == 0) {
        this.$message({
          type: 'error',
          message: '请先选择职位!',
        })
        return false
      } else {
        return true
      }
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload2.isUploading = true
      this.upladLoading = this.$loading({
        lock: true,
        text: '拼命上传中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      })
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      let that = this
      let receiveShopCode,
        data = {}
      // this.storeListAdd.forEach((item,index)=>{
      //     if(item.id == -1){
      //         receiveShopCode.push(item.receiveShopCode);
      //     }
      // })
      // receiveShopCode = JSON.stringify(this.storeListAdd)
      if (this.form.id || this.form.id == 0) {
        data.taskId = this.form.id
      } else {
        data.taskId = ''
      }
      // data.shopcodes = receiveShopCode;
      if (response.code == 200) {
        data.url = response.fileName
        data.businessType = that.form.businessType
        data.level = this.form.byType
        // data.position = that.positionValue.join(',');
        importSignUser(data).then((res) => {
          // res.data.success.forEach((resItem,resIndex)=>{
          //     // let randomCode = '' + (parseInt(Math.random()*1000000)+1000000);
          //     // resItem.issueNum = that.updateTaskCode + randomCode.substring(1,7);
          //     resItem.isImport = true;
          //     that.storeListAdd.forEach((storeItem,storeIndex)=>{
          //       if(resItem.receiveDeptname == storeItem.receiveDeptname){
          //         that.storeListAdd[storeIndex] = resItem
          //       }
          //     })
          // })
          let storeListAdd = [...that.storeListAdd, ...res.data.success]
          // const resAdd = new Map();
          // that.storeListAdd = storeListAdd.filter((item)=> !resAdd.has(item.receiveDeptname) && resAdd.set(item.receiveDeptname,1));
          const newStoreListAddReceiveDeptname = storeListAdd.map((item) => item.receiveDeptname)
          const newStoreListAddReceiveNum = storeListAdd.map((item) => item.receiveNum)
          let sameArr = []
          newStoreListAddReceiveDeptname.forEach((newStoreListAddItem, newStoreListAddIndex) => {
            var arr = []
            storeListAdd.forEach((storeListAddItem, storeListAddIndex) => {
              if (
                storeListAddItem.receiveDeptname == newStoreListAddItem &&
                storeListAddItem.receiveNum == newStoreListAddReceiveNum[newStoreListAddIndex]
              ) {
                arr.push(storeListAddIndex)
                if (arr.length > 1) {
                  storeListAdd.splice(storeListAddIndex, 1)
                  sameArr.push(storeListAddItem)
                }
              }
            })
          })
          this.storeListAdd = storeListAdd
          const newSameArrReceiveDeptname = sameArr.map((item) => item.receiveDeptname)
          const newSameArrReceiveNum = sameArr.map((item) => item.receiveNum)
          newSameArrReceiveDeptname.forEach((newSameArrReceiveDeptname, newSameArrIndex) => {
            var arr = []
            sameArr.forEach((sameArrItem, sameArrIndex) => {
              if (
                sameArrItem.receiveDeptname == newSameArrReceiveDeptname &&
                sameArrItem.receiveNum == newSameArrReceiveNum[newSameArrIndex]
              ) {
                arr.push(sameArrIndex)
                if (arr.length > 1) {
                  sameArr.splice(sameArrIndex, 1)
                }
              }
            })
          })
          let html = ''
          sameArr.forEach((htmlItem, hemltIndex) => {
            if (hemltIndex == 0) {
              html = html + `费用归属${htmlItem.receiveDeptname}员工编号${htmlItem.receiveNum}`
            } else {
              html = html + `,费用归属${htmlItem.receiveDeptname}员工编号${htmlItem.receiveNum}`
            }
          })
          that.storeListAdd.forEach((resItem, resIndex) => {
            if (resItem.isImport == undefined) {
              resItem.isImport = false
            }
            if (
              resItem.issueNum == undefined ||
              resItem.issueNum == null ||
              resItem.issueNum == ''
            ) {
              let randomCode = ''
              if (resIndex + 1 < 10) randomCode = '000' + (resIndex + 1)
              if (resIndex + 1 >= 10 && resIndex + 1 < 100) randomCode = '00' + (resIndex + 1)
              if (resIndex + 1 >= 100 && resIndex + 1 < 1000) randomCode = '0' + (resIndex + 1)
              if (resIndex + 1 >= 1000) randomCode = '' + (resIndex + 1)
              resItem.issueNum = that.updateTaskCode + randomCode
            }
          })
          this.tablenum++
          this.$forceUpdate()
          // that.storeListAdd=[...res.data.success];
          this.upload2.open = false
          this.upload2.isUploading = false
          this.upladLoading.close()
          this.$refs.upload2.clearFiles()
          if (res.data.error.length == 0) {
            this.$message({
              type: 'success',
              message: '添加成功!',
            })
          } else {
            this.$alert(res.data.error, '导入结果', { dangerouslyUseHTMLString: true }).then(
              (action) => {
                if (sameArr.length > 0) {
                  this.$message({
                    type: 'warning',
                    message: html + '有重复数据',
                  })
                }
              }
            )
          }
        })
      } else {
        this.upload2.open = false
        this.upload2.isUploading = false
        this.upladLoading.close()
        this.$refs.upload2.clearFiles()
        this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
      }
      this.getList()
    },
    importTemplate() {
      let url = process.env.VUE_APP_Target + '/profile/upload/template/发放任务导入模版.xlsx'
      window.open(url, '_blank')
      // importTemplate().then((response) => {
      //   window.location.href =
      //     process.env.VUE_APP_BASE_API +
      //     '/common/download?fileName=' +
      //     encodeURI(response.msg) +
      //     '&delete=' +
      //     true;

      //   //this.download(response.msg);
      // });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload2.submit()
    },
    /** 导入按钮操作 */
    handleImport3() {
      this.upload3.title = '任务导入'
      this.upload3.open = true
    },
    // 下载导入模板
    importTemplate3() {
      let url = process.env.VUE_APP_Target + '/profile/upload/template/批量发放任务导入模版.xlsx'
      window.open(url, '_blank')
    },
    // 文件上传中处理
    handleFileUploadProgress3(event, file, fileList) {
      this.upload3.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess3(response, file, fileList) {
      this.upload3.open = false
      this.upload3.isUploading = false
      this.$refs.upload3.clearFiles()
      this.$alert(response.msg, '导入结果', { dangerouslyUseHTMLString: true })
      this.getList()
    },
    // 提交上传文件
    submitFileForm3() {
      this.$refs.upload3.submit()
    },
    // 物料名称change事件
    materialNameChange(val) {},
  },
}
</script>
<style lang="scss" scoped>
.line-ht36 {
  line-height: 36px;
}

.required:before {
  content: '*';
  color: #ff4949;
  margin-right: 4px;
}

.required {
  font-size: 14px;
  color: #606266;
  font-weight: 700;
}

::v-deep .el-upload-list__item {
  transition: none !important;
}

.qszw {
  ::v-deep .el-tag.el-tag--info .el-tag__close {
    display: none;
  }
}

.qszw-required {
  ::v-deep .el-form-item__label:before {
    content: '*' !important;
    color: #ff4949 !important;
    margin-right: 4px !important;
  }
}

.drfbrw {
  float: right;

  ::v-deep .el-button--info.is-plain {
    color: #1890ff;
    background: #fff8e6;
    border-color: #1890ff;
  }
}
</style>
<style lang="scss">
.el-upload-list__item {
  div {
    height: 100%;
  }
}

.hideRow {
  display: none;
}
.tablenumClassName {
  .el-table__fixed-right {
    height: 100% !important;
  }
}
</style>
