<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务编码" prop="taskCode">
        <el-input
          v-model="queryParams.taskCode"
          placeholder="请输入任务编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
          @input="onInput()"
        />
      </el-form-item>
      <el-form-item label="物料类型" prop="materialType">
        <!--              <el-input v-model="form.materialType" size="small" placeholder="请输入物料类型" @input="onInput" :disabled="form.status == '1'"/>-->
        <el-select v-model="queryParams.materialType" size="small" 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-input-->
        <!--          v-model="queryParams.materialName"-->
        <!--          placeholder="请输入物料名称"-->
        <!--          clearable-->
        <!--          size="small"-->
        <!--          @keyup.enter.native="handleQuery"-->
        <!--          @input="onInput"-->
        <!--        />-->
        <el-select v-model="queryParams.materialName" size="small" 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="small" @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="issuingTime">
        <el-date-picker clearable size="small"
                        v-model="queryParams.ffsj"
                        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="toBeshippedM"
          @click="handleDelete"
        >删除</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="任务编码" align="center" prop="taskCode" />
      <el-table-column label="任务名称" align="center" prop="taskName" width="230" :show-overflow-tooltip="true"/>
      <el-table-column label="物料类型" align="center" prop="materialType" />
      <el-table-column label="物料名称" align="center" prop="materialName" width="230" :show-overflow-tooltip="true" />
      <el-table-column label="发放人" align="center" prop="issuer" />
      <el-table-column label="发放人编码" align="center" prop="issuerCode" width="110" />
      <el-table-column label="发放时间" align="center" prop="issuingTime" width="180"/>
      <el-table-column label="物料状态" align="center" prop="status" >
        <template slot-scope="scope">
          <!--          <span>{{statusFormat(scope.row)}}</span>-->
          <dicts-tag :options="statusOptions" :value="scope.row.status"/>
        </template>

      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right" width="130">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-notebook-2"
            @click="toRecord(scope.row)"
            :disabled="scope.row.status != '1'"
          >发放记录</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="8">
            <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="8">
            <el-form-item label="发放物料类型" prop="materialType">
              <!--              <el-input v-model="form.materialType" size="small" placeholder="请输入物料类型" @input="onInput"/>-->
              <el-select v-model="form.materialType" size="small" clearable filterable @change="materialTypeChange" :disabled="form.status == '1'">
                <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"/>-->
              <el-select v-model="form.materialName" size="small" clearable filterable @change="onInput()" :disabled="form.status == '1'">
                <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-top: 10px;">
          <el-col :span="3">
            <span class="required line-ht36">选择发放门店</span>
          </el-col>
          <el-col :span="15">
            <el-form ref="addStoreForm2" :model="addStoreForm2"  :inline="true" size="mini" label-width="70px">
              <el-form-item label="门店" prop="shopcode">
                <el-input
                  v-model="addStoreForm2.shopInfo"
                  clearable
                  placeholder="请输入门店编码/名称"
                  @input="onInput()"
                  style="width: 160px;"
                />
              </el-form-item>
              <el-form-item label="物料状态" prop="shopcode">
                <el-select
                  v-model="addStoreForm2.status"
                  placeholder="请选择物料状态"
                  clearable size="small"
                  @change="onInput()"
                  style="width: 160px;"
                >
                  <el-option
                    v-for="dict in statusOptions2"
                    :key="dict.dictValue"
                    :label="dict.dictLabel"
                    :value="dict.dictValue"
                  />
                </el-select>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="addStoreQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetAddStoreQuery">重置</el-button>
              </el-form-item>
            </el-form>
          </el-col>
          <el-col :span="2">
            <el-button
              type="info"
              plain
              icon="el-icon-upload2"
              size="mini"
              @click="addStoreImport"
              v-if="nameIsSame"
            >导入</el-button>
          </el-col>
          <el-col :span="2">
            <el-button
              type="primary"
              plain
              icon="el-icon-plus"
              size="mini"
              @click="handleAddStore"
              v-if="nameIsSame"
            >添加</el-button>
          </el-col>
          <el-col :span="2">
            <el-button
              type="danger"
              plain
              icon="el-icon-delete"
              size="mini"
              @click="handleDeleteStore"
              v-if="nameIsSame"
              :disabled="multipleAddStore"
            >
              <span v-if="form.status == 1">作废</span>
              <span v-else>删除</span>
            </el-button>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="24">
            <el-table :data="storeListAdd" :key='tablenum' ref="addStore" @selection-change="handleSelectionChangeStoreAdd" :row-class-name="rowHideFn" height="400">
              <el-table-column type="selection" width="55" align="center" :selectable="selected" />
              <el-table-column label="门店编码" align="center" prop="receiveShopCode" width="110" />
              <el-table-column label="门店名称" align="center" prop="receiveShopName" :show-overflow-tooltip="true" />
              <!--              <el-table-column label="门店类型" align="center" prop="deptTwo" />-->
              <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" prop="extend" >
                <template slot-scope="scope">
                  <el-input v-model="scope.row.extend" placeholder="" size="mini" style="width: 70px;"
                            @input="extendOnInput(scope.$index)"
                            :disabled="!nameIsSame || scope.row.status =='2' || scope.row.status =='3'"></el-input>
                </template>
              </el-table-column>
              <el-table-column label="物料状态" align="center" prop="status" width="100">
                <template slot-scope="scope">
                  <!--                  <span>{{statusFormat2(scope.row)}}</span>-->
                  <dicts-tag :options="statusOptions2" :value="scope.row.status.toString()"/>
                </template>
              </el-table-column>
              <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"
                    @click="handleDeleteStore(scope.row)"
                    :disabled="scope.row.status =='2' || scope.row.status =='3' "
                    v-if="nameIsSame && scope.row.status !='3'"
                  >
                    <span v-if="form.status == 1 && scope.row.id != -1">作废</span>
                    <span v-else>删除</span>
                  </el-button>
                  <el-button
                    type="text"
                    icon="el-icon-refresh-right"
                    size="mini"
                    @click="handleReturnStore(scope.row)"
                    v-if="nameIsSame && scope.row.status =='3'"
                  >
                    <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="storeOpen" width="80%" append-to-body>
      <el-form ref="addStoreForm" :model="addStoreForm"  :inline="true" size="mini" v-show="showSearchStore" label-width="90px">
        <el-form-item label="门店编码" prop="shopcode">
          <el-input v-model="addStoreForm.shopcode" clearable placeholder="请输入门店编码" @input="onInput()" />
        </el-form-item>
        <el-form-item label="门店名称" prop="shopname">
          <el-input v-model="addStoreForm.shopname" 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="门店编码" align="center" prop="receiveShopCode" width="110" />
        <el-table-column label="门店名称" align="center" prop="receiveShopName" :show-overflow-tooltip="true" />
        <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>
  </div>
</template>

<script>
import { listTask, getTask, delTask, addTask, updateTask, listStore,addtaskcancel,sendmater,delSign,importSigntemp,returnStore } from "@/api/guide/task";
import { getToken } from "@/utils/auth";
import { importTemplate } from "@/api/guide/sign";
import { listDictype } from "@/api/guide/dictype";
export default {
  name: "Task",
  components: {
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      toBeshippedS:true,
      toBeshippedM:true,

      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 物料签收任务中心表格数据
      taskList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      statusOptions:[],
      statusOptions2:[],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      dialogImageUrlUpload: '',
      dialogVisibleUpload: false,
      disabledUpload: false,
      storeOpen:false,
      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: 'blur' },
        ],
        materialName: [
          { required: true, message: '请输入物料名称', trigger: 'blur' },
        ],
      },
      fileList:[],
      upladLoading:null,
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/uploadsign",
        loadProgress: 10,
      },
      upload2: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/common/uploadsign",
        loadProgress: 10,
      },
      canelIds:[],
      canelShopCodes:[],
      multipleAddStore:true,
      addStoreForm2:{},
      storeListAddSubmit:[],
      tablenum:0,
      upladLoading:null,
      name:'',
      formCreatBy:'',
      nameIsSame:true,
      materialNameOptionQuery:[],
      materialNameOption:[],
      materialTypeOption:[],
    };
  },
  created() {
    this.getDicts("guide_item_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts("guide_sign_status").then(response => {
      this.statusOptions2 = response.data;
      console.log(this.statusOptions2 )
    });
    // this.getMaterialNameOptionAll();
    this.getMaterialTypeOption();
    this.name = this.$store.state.user.name;
    this.getList();

  },
  methods: {
    onInput(){
      this.$forceUpdate()
    },
    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();
    },
    // 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;
        }
        console.log(that.materialNameOption)
      });
    },
    materialTypeChangeQuery(val){
      console.log(val)
      this.queryParams.materialName = '';
      if(val != '' && val != null){
        let pid;
        this.materialTypeOption.forEach((item)=>{
          if(item.signType == val){
            console.log(item)
            pid = item.id;
            let obj = {
              type:1,
              pid,
            };
            this.getMaterialNameOption(obj,'materialNameOptionQuery');
          }
        })
      }else{
        this.materialNameOptionQuery = [];
      }
      this.$forceUpdate()
    },
    materialTypeChange(val,isUplate){
      console.log(val)
      if(!isUplate){
        this.form.materialName = '';
      }

      if(val != '' && val != null){
        let pid;
        this.materialTypeOption.forEach((item)=>{
          if(item.signType == val){
            console.log(item)
            pid = item.id;
            let obj = {
              type:1,
              pid,
            };
            this.getMaterialNameOption(obj,'materialNameOption');
          }
        })
      }else{
        this.materialNameOption = [];
      }
      this.$forceUpdate()
    },
    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 = {};
      this.formCreatBy = '';
      this.resetForm("form");
      this.fileList = [];
      this.storeListAdd = [];
      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;
      }
    },
    selected(row, index) {
      if (row.statue == '3') {
        return false //不可勾选
      } else {
        return true; //可勾选
      }
    },
    handleSelectionChangeStoreAdd(selection) {
      let showSelection = [];
      selection.forEach((item,index)=>{
        if(!item.isHide){
          showSelection.push(item)
        }
      })

      this.canelIds = showSelection.map(item => item.id);
      this.canelShopCodes = showSelection.map(item => item.receiveShopCode);
      let multiple = !showSelection.length;
      let status = showSelection.map(item => item.status);
      console.log(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.open = true;
      this.title = "物料发放添加";
      this.nameIsSame = true;
    },
    /** 修改按钮操作 */
    handleUpdate(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.materialName = response.data.guideMaterialTask.materialName;
        this.form.id = response.data.guideMaterialTask.id;
        this.form.status = response.data.guideMaterialTask.status;
        this.storeListAdd = response.data.materialSigns;
        this.fileList = this.fileListsrcFn(response.data.grantimginfo);
        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');
        this.open = true;
        this.title = "物料发放详情";
      });
    },
    fileListsrcFn(arr){
      let list = [];
      arr.forEach((item,index)=>{
        let obj = {
          response:{
            downloadUrl:item.path
          },
          url: item.path
        }
        list.push(obj);
      })
      return list;
    },
    /** 提交按钮 */
    submitForm(val) {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if(this.storeListAdd.length <= 0){
            this.$message.error("请选择发放门店");
            return;
          }else {
            let arr = [];
            this.storeListAdd.forEach((item)=>{
              if(item.extend == '' || item.extend == null){
                arr.push(true)
              }
            })
            if(arr.length > 0){
              this.$message.error("发放数量不能为空");
              return;
            }
          }
          if(this.fileList.length <= 0){
            this.$message.error("请上传物料图片");
            return;
          }
          this.form.data = JSON.stringify(this.storeListAdd);
          this.form.status = val;
          this.form.fileurl = this.fileList.map(item=>item.response.downloadUrl).join(',');
          console.log(this.form)
          if (this.form.id != null) {
            updateTask(this.form).then(response => {
              this.$message.success("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTask(this.form).then(response => {
              this.$message.success("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 批量发货
    sendmaterFn(){
      const id = this.ids.join(',');
      this.$confirm('是否确认批量发货已选中数据?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return sendmater({id});
      }).then(() => {
        this.getList();
        this.$message.success("发货成功");
      }).catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除已选中数据?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return delTask(ids);
      }).then(() => {
        this.getList();
        this.$message.success("删除成功");
      }).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){
      console.log(file)
      console.log(fileList)
      this.fileList = fileList;
      console.log(this.fileList)
    },
    imgUploadError(err, file, fileList){
      this.$message.error('上传失败，请重新上传！');
    },
    getStoreList(){
      this.loadingStore = true;
      // let obj = this.addStoreForm;
      // obj.shopcode = shopCodes;
      console.log(this.addStoreForm)
      listStore(this.addStoreForm).then(response => {
        console.log(response)
        this.storeList = response.rows;
        this.totalStore = response.total;
        this.loadingStore = false;
      });
    },
    handleAddStore(){
      this.storeOpen = true;
      // let shopcodes = this.storeListAdd.map(item => item.receiveShopCode)
      let shopcodes = [];
      this.storeListAdd.forEach((item,index)=>{
        // if(item.status != 3){
        shopcodes.push(item.receiveShopCode);
        // }
      })
      this.addStoreForm.shopcodes = shopcodes.join(',');
      this.addStoreForm.shopcode = '';
      this.addStoreForm.shopname = '';
      this.getStoreList();
    },
    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 = 3;
                      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 = 3;
                    this.$forceUpdate();
                  }
                })
              })
              this.$refs.addStore.clearSelection();
            });
          }else{
            console.log(idArr)
            // 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';
          }
        })
      });
    },
    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;
      let store = [];
      let storeCodes = [];
      row.receiveShopCode ? store.push(row) : store = this.storeSelect;
      row.receiveShopCode ? storeCodes.push(row.receiveShopCode) : storeCodes =this.storeCodes;
      console.log(storeCodes)
      let storeList = that.storeListAdd;
      this.$confirm('是否添加选中信息?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        let arr = [];
        store.forEach((item,index)=>{
          // if(that.form.id){
          //     that.storeListAdd = [];
          //     that.storeListAdd[0] = item;
          // }else{
          that.storeListAdd.forEach((da,ind)=>{
            // ||(da.receiveShopCode == item.receiveShopCode && da.status == 3)
            if(da.receiveShopCode != item.receiveShopCode){
              arr.push(false)
            }else{
              arr.push(true);
            }
          })
          arr.indexOf(true) == -1 ? that.storeListAdd.push(item) : that.storeListAdd;
          // }
        })
      }).then(() => {
        let shopcodesArr = [];
        if(that.addStoreForm.shopcodes != ''){
          shopcodesArr = that.addStoreForm.shopcodes.split(',');
        }
        let newShopCodesArr = [...shopcodesArr,...storeCodes];
        this.addStoreForm.shopcodes = newShopCodesArr.join(',');
        this.getStoreList();
        this.$message({
          type: 'success',
          message: '添加成功!'
        });
      }).catch(() => {});
    },
    handleSelectionChangeStore(selection){
      this.storeCodes = selection.map(item => item.receiveShopCode);
      console.log(this.storeCodes)
      this.storeSelect = selection;
      this.multipleStore = !selection.length
    },
    toRecord(row){
      this.$router.push({path:'/material/sign',query:{taskId:row.id,extend:row.extend,name:row.createBy}});
    },
    addStoreQuery(){
      // this.storeListAddSubmit = this.storeListAdd;
      this.storeListAdd.forEach((item,index)=>{
        console.log(item.receiveShopCode.indexOf(this.addStoreForm2.shopInfo))
        if(
          (this.addStoreForm2.shopInfo =='' && this.addStoreForm2.status == '')
          ||
          (this.addStoreForm2.shopInfo !='' && this.addStoreForm2.status == '' && (this.addStoreForm2.shopInfo.indexOf(item.receiveShopCode)!=-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 && (this.addStoreForm2.shopInfo.indexOf(item.receiveShopCode)!=-1 || item.receiveShopName.indexOf(this.addStoreForm2.shopInfo) != -1) )
        ){
          item.isHide = false;
        }else{
          item.isHide = true;
        }
      })
      console.log(this.storeListAdd);
      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(){
      this.upload2.title = "物料签收导入";
      this.upload2.open = 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;
      }
      data.shopcodes = receiveShopCode;
      if(response.code==200){
        data.url = response.url;
        importSigntemp(data).then(res => {
          // that.storeListAdd=[...that.storeListAdd,...res.data.success];
          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 });
          }
        })
      }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() {
      importTemplate().then(response => {
        window.location.href = process.env.VUE_APP_BASE_API + "/common/download?fileName=" + encodeURI(response.msg) + "&delete=" + true;
      });
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload2.submit();
    },
  }
};
</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;
}
</style>
<style lang="scss">
.el-upload-list__item{
  div{
    height: 100%;
  }
}
.hideRow{
  display: none;
}
</style>
