<!--出入库任务-->
<template>
  <div class="container">
    <BaseHeaderLayout :leftSpan="6">
      <template slot="left">
        <ws-button type="primary" @click="handleAdd()" v-hasPermission="
            `warehouseManagement.warehouse.warehouseInfoTask.add`
          ">添加
        </ws-button>
      </template>
      <template slot="right">
        <ws-select v-model="warehouseNametext" placeholder class="typeselect" @change="warehousechange" :value="warehouseName">
           <ws-option  key="全部仓库" label="全部仓库" value="全部仓库"
            style="color: #8890b1" />
          <ws-option v-for="item in warehouseList" :key="item.id" :label="item.warehouseName" :value="item.warehouseName"
            style="color: #8890b1" />
        </ws-select>
        <ws-select v-model="publishertext" placeholder class="typeselect" @change="publisherchange" :value="publisher">
          <ws-option  key="全部发布者" label="全部发布者" value="全部发布者" style="color: #8890b1" />
          <ws-option v-for="item in staffList" :key="item.id" :label="item.staffName" :value="item.staffName"
            style="color: #8890b1" />
        </ws-select>
        <ws-select v-model="searchTypeText" placeholder class="typeselect" @change="selecttaskType" :value="searchType">
          <ws-option v-for="item in taskTypeList" :key="item.value" :label="item.value" :value="item.value"
            style="color: #8890b1" />
        </ws-select>
        <ws-select v-model="inOutType" placeholder class="typeselect" @change="selectinOutType" :value="inOutType">
          <ws-option v-for="item in inOutTypeList" :key="item.value" :label="item.value" :value="item.value"
            style="color: #8890b1" />
        </ws-select>
        <ws-input @keyup.enter.native="find()" class='findValue' v-model="searchKeyWord" placeholder="可按合同编号或任务编号查找" clearable maxlength="500" type="input"></ws-input>
        <ws-button class="find" type="primary" @click="lookUp()">
          <img width="16" height="16" style="
              vertical-align: text-top;
              position: relative;
              top: 0px;
              left: -8px;
            " src="../../../public/img/sousuo.png" alt />
        </ws-button>
      </template>
    </BaseHeaderLayout>
      <el-table class="wenzi" :data="gainList.records" style="width: 100%" height="calc(100% - 110px)">
        <el-table-column type="index" label="序号">
          <template scope="scope">
            <span v-if="scope.$index < 9">0{{ scope.$index + 1 }}</span>
            <span v-else>{{ scope.$index + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="inOutTaskNo" label="任务编号" width="160"></el-table-column>
        <el-table-column prop="contractNo" label="合同编号/移库编号" width="160">
          <template scope="scope">
            <div
              v-if="
                scope.row.inOutType == '移库入库' ||
                scope.row.inOutType == '移库出库'
              "
            >
              {{ scope.row.moveTaskNo }}
            </div>
            <div
              v-if="
                scope.row.inOutType != '移库入库' &&
                scope.row.inOutType != '移库出库'
              "
            >
              {{ scope.row.contractNo }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="warehouseName" class="table_td" label="仓库名"></el-table-column>
        <el-table-column prop="inOutType" class="table_td" label="出入库类型"></el-table-column>
        <el-table-column prop="goodsName" class="table_td" label="货名">
          
          {{scope.row.goodsName?scope.row.goodsName:scope.row.sourceId}}
        </el-table-column>
        <el-table-column prop="weight" class="table_td" label="重量（吨）"></el-table-column>
        <el-table-column prop="predictDate" class="table_td" label="预计日期"></el-table-column>
        <el-table-column prop="publisher" class="table_td" label="发布者"></el-table-column>
        <el-table-column prop="completedQuantity" class="table_td" label="已完成量(吨)">
          <template slot-scope="scope">
            {{scope.row.completedQuantity == 0 ? 0:scope.row.completedQuantity.toFixed(3)}}
          </template>
        </el-table-column>
        <el-table-column prop="taskStatus" label="状态" width="90">
          <template slot-scope="scope">
            <template>
              <span slot="reference">
                <span v-if="scope.row.taskStatus == '待审核'" class="executory"></span>
                <span v-if="scope.row.taskStatus == '执行中'" class="inExecution"></span>
                <span v-if="scope.row.taskStatus == '已完成'" class="done"></span>
                {{ scope.row.taskStatus }}
              </span>
            </template>
            <img v-if="scope.row.taskStatus == '执行中'" width="17" height="18"
              style="vertical-align: text-top; position: relative; top: -1px" src="../../../public/img/edit.png"
              @click="editClick(scope.row)" alt />
          </template>
        </el-table-column>
        <el-table-column prop="establishDate" class="table_td" label="创建时间" width="150"></el-table-column>
        <el-table-column prop="seller" label="操作" width="230">
          <template slot-scope="scope">
            <span class="corles" @click="nocomplete(scope.row)" v-hasPermission="
                `warehouseManagement.warehouse.warehouseInfoTask.View`
              ">查看</span>
            <span v-hasPermission="`warehouseManagement.warehouse.warehouseInfoTask.audit`">
              <el-divider direction="vertical" v-if="scope.row.taskStatus == '待审核'"></el-divider>
            </span>

            <span class="corles" v-hasPermission="
                `warehouseManagement.warehouse.warehouseInfoTask.audit`
              " v-if="scope.row.taskStatus == '待审核'&&scope.row.taskId" @click="audit(scope.row)">审核</span>
            <el-divider direction="vertical" class="divider" v-if="
                scope.row.taskStatus == '待审核'&&scope.row.taskId ||
                scope.row.taskStatus == '执行中' ||
                scope.row.taskStatus == '已驳回'
              "></el-divider>
            <span class="corles" v-hasPermission="
                `warehouseManagement.warehouse.warehouseInfoTask.edit`
              " v-if="
                scope.row.taskStatus == '执行中' ||
                scope.row.taskStatus == '已驳回'
              " @click="delivery(scope.row)">编辑</span>
              <span v-hasPermission="`warehouseManagement.warehouse.warehouseInfoTask.delete`">
              <el-divider direction="vertical" v-if=" scope.row.taskStatus == '执行中' ||
                scope.row.taskStatus == '已驳回'"></el-divider>
            </span>
            <span v-hasPermission="`warehouseManagement.warehouse.warehouseInfoTask.delete`">
              <el-divider direction="vertical" v-if="scope.row.show"></el-divider>
            </span>
            <span class="corles" v-hasPermission="
                `warehouseManagement.warehouse.warehouseInfoTask.delete`
              " v-if="scope.row.show" @click="rectify(scope.row)">矫正</span>
            <span v-hasPermission="`warehouseManagement.warehouse.warehouseInfoTask.delete`">
              <el-divider direction="vertical" v-if="scope.row.show"></el-divider>
            </span>

            <span class="corles" v-hasPermission="
                `warehouseManagement.warehouse.warehouseInfoTask.delete`
              " v-if="!scope.row.approveStatus" @click="deleteclick(scope.row)">删除</span>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
        :page-size="pageSize" layout="total, sizes, prev, pager, next, jumper" :total="deptBudgetTotal"></el-pagination>
  </div>
</template>
<script>
  import {
    getoreditoutput,
    outdelete,
    movestates,
    setcorrect
  } from '@/model/tasksport/index'
  import {
  selectWarehouseSelf,
} from '@/model/houseSelfCollect/index'
  import {
    getstafffind,
  } from '@/model/contarct/index'
  import {
    downloadFile
  } from '@/utils/batchDown'
  import Pagination from '@/components/Pagination'
  import WsUpload from '@/components/WsUpload'
  import {
    dayjs,
    fmoney,
    EventBus
  } from 'base-core-lib'
  export default {
    name: 'viewSpareMoney',
    components: {
      WsUpload,
      Pagination,
    },
    watch: {
      vesselId(val) {
        this.getList()
      },
      isShow(val) {
        this.showType = val
      },
    },
    data() {
      return {
        //弹出框
        dialogViewSpareMoney: false,
        dialogApproveFormVisible: false,
        // 船舶类型
        monetaryKey: null,
        // 表格显示数据
        tableDate: [],

        // 是否显示
        showType: true,
        // 年
        year: '',
        gainList: [],
        currentPage: 1,
        primary: '1',
        pageSize: 10,
        searchType: '',
        publishertext:'全部发布者',
        publisher:'',
        searchTypeText: '全部状态',
        searchKeyWord: '',
        inOutType:'',
        inOutTypeList:[
          {
            value: '销售出库',
            type: 1
          },
          {
            value: '移库出库',
            type: 3
          },
          {
            value: '暂存出库',
            type: 2
          },
          {
            value: '贸易服务出库',
            type: 4
          },
          {
            value: '采购出库',
            type: 5
          },
          {
            value: '采购入库',
            type: 6
          },
          {
            value: '移库入库',
            type: 7
          },
          {
            value: '暂存入库',
            type: 8
          },
          {
            value: '贸易服务入库',
            type: 9
          },
          {
            value: '收购入库',
            type: 10
          },
          {
            value: '退库',
            type: 11
          },
        ],
        contractType: 2,
        taskTypeList: [{
            value: '待审核',
            type: 1
          },
          {
            value: '执行中',
            type: 3
          },
          {
            value: '已驳回',
            type: 2
          },
          {
            value: '已完成',
            type: 4
          },
          {
            value: '全部状态',
            type: ''
          },
        ],
        // 提交类型
        submitType: true,
        size: 10,
        spanArr: [],
        warehouseNametext: '全部仓库',
        warehouseName:'',
        deptBudgetTotal: 0,
        warehouseList:[],
        compId: localStorage.getItem('ws-pf_compId'),
        deptCircularPage: {},
        historyList: [],
        staffList:[],
        pickerBeginDateBefore: {
          disabledDate: (time) => {
            return time.getTime() > Date.now()
          },
        },
        accessoryTFs: false,
      }
    },
    activated() {
      
      this.getList()
      this.showType = this.isShow
    },
    mounted() {
      selectWarehouseSelf({
        compId: localStorage.getItem('ws-pf_compId'),
      })
        .toPromise()
        .then((response) => {
          this.warehouseList=response
          // console.log(response)
        })
        getstafffind({
          roles: '499413401da1471fa2e26f2e35d4f018'
        })
        .toPromise()
        .then((response) => {
          this.staffList = response
        })
      this.getList()
      this.showType = this.isShow
    },
    methods: {
      rectify(row){
        this.$confirm('确定矫正出库任务重量并结束任务？', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
          .then(() => {
            setcorrect({id:row.id}).toPromise()
              .then((response) => {
                 this.$notify.success({
                  title: '成功',
                  message: '矫正成功',
                })
                this.getList()
              }).catch(() => {
                 this.$notify.error({
                  title: '失败',
                  message: '矫正失败',
                })
              })
          }).catch(() => {
            return false
          })
      },
      selectinOutType(){
        this.getList()
      },
      //添加
      handleAdd() {
        this.$router.push({
          path: 'tranManagementWarehouseInOuttaskAdd'
        })
      },
      //查找
      lookUp() {
        this.currentPage = 1
        this.getList()
      },
      deleteclick(row) {
        var text = ''
        if (
          (row.taskTypeKey == 3 && row.inOutType == '移库出库') ||
          (row.taskTypeKey == 4 && row.inOutType == '销售出库') ||
          (row.taskTypeKey == 4 && row.inOutType == '退库')
        ) {
          text = '相同任务编号的任务将一并删除且不可恢复，是否确定删除？'
        } else {
          text = `任务删除后不可恢复，是否确定删除？`
        }
        //cancelButtonClass: "btn-custom-cancel"
        this.$confirm(text, {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
          .then(() => {
            outdelete({
                id: row.id,
                relevanceId: row.relevanceId,
                inOutFlag: row.inOutFlag,
              })
              .toPromise()
              .then((response) => {
                this.getList()
              })
          })
          .catch(() => {
            return false
          })
      },
      getList() {
        getoreditoutput({
            compId: localStorage.getItem('ws-pf_compId'),
            currentPage: this.currentPage,
            pageSize: this.pageSize,
            searchType: this.searchType,
            searchKeyWord: this.searchKeyWord,
            inOutType:this.inOutType,
            warehouseName:this.warehouseName,
            publisher:this.publisher
          })
          .toPromise()
          .then((response) => {
            for (let i = 0; i < response.records.length; i++) {
              // response.records[i].completedQuantity=response.records[i].completedQuantity/1000
              if(response.records[i].taskStatus=='执行中'&&response.records[i].inOutType=='销售出库'&&response.records[i].taskTypeKey==1&&response.records[i].completedQuantity<response.records[i].weight
              ||response.records[i].taskStatus=='执行中'&&response.records[i].inOutType=='移库出库'&&response.records[i].completedQuantity<response.records[i].weight){
                response.records[i].show=true
              }else if(response.records[i].taskStatus=='已完成'&&response.records[i].inOutType=='销售出库'&&response.records[i].taskTypeKey==1&&response.records[i].completedQuantity<response.records[i].weight
               ||response.records[i].taskStatus=='执行中'&&response.records[i].inOutType=='移库出库'&&response.records[i].completedQuantity<response.records[i].weight){
                 response.records[i].show=true
              }else{
                response.records[i].show=false
              }
              
            }
            this.gainList = response
            this.currentPage = response.current
            this.pageSize = response.size
            this.deptBudgetTotal = response.total
          })
      },
      //编辑
      delivery(item) {
        this.$router.push({
          path: 'tranManagementWarehouseInOuttaskedit',
          query: {
            relevanceId: item.relevanceId,
            inOutFlag: item.inOutFlag
          },
        })
      },
      audit(item) {
        this.$router.push({
          path: 'tranManagementWarehouseInOuttaskaudit',
          query: {
            relevanceId: item.relevanceId,
            taskId: item.taskId,
            businessKey: item.id,
            workflowId: item.workflowId,
          },
        })
      },
      getSpanArr(data) {
        let that = this

        //页面展示的数据，不一定是全部的数据，所以每次都清空之前存储的 保证遍历的数据是最新的数据。以免造成数据渲染混乱

        that.spanArr = []

        that.pos = 0

        //遍历数据

        data.forEach((item, index) => {
          //判断是否是第一项

          // if (index === 0) {
          //   this.spanArr.push(1)
          //   this.pos = 0
          // } else {
          //不是第一项时，就根据标识去存储
          if (data[index].warehouseNumViewList.length > 1) {
            // 查找到符合条件的数据时每次要把之前存储的数据+1
            this.spanArr[this.pos] = data[index].warehouseNumViewList.length
            this.spanArr.push(0)
          } else {
            // 没有符合的数据时，要记住当前的index
            this.spanArr.push(1)
            this.pos = index
          }
          // }
        })
      },
      //查看//传参
      nocomplete(row) {
        this.$router.push({
          path: 'inOutWarehousetaskEdit',
          query: {
            relevanceId: row.relevanceId,
            businessKey: row.id,
            workflowId: row.workflowId,
          },
        })
      },
      dateFormat(fmt, date) {
        let ret
        const opt = {
          'Y+': date.getFullYear().toString(), // 年
          'm+': (date.getMonth() + 1).toString(), // 月
          'd+': date.getDate().toString(), // 日
          'H+': date.getHours().toString(), // 时
          // "M+": date.getMinutes().toString(),         // 分
          // "S+": date.getSeconds().toString()          // 秒
          // 有其他格式化字符需求可以继续添加，必须转化成字符串
        }
        for (let k in opt) {
          ret = new RegExp('(' + k + ')').exec(fmt)
          if (ret) {
            fmt = fmt.replace(
              ret[1],
              ret[1].length == 1 ? opt[k] : opt[k].padStart(ret[1].length, '0')
            )
          }
        }
        return fmt
      },
      handleClose() {
        this.accessoryTFs = false
      },
      handleSizeChange(val) {
        console.log(`每页 ${val} 条`)
        this.pageSize = val
        this.getList()
      },
      handleCurrentChange(val) {
        this.currentPage = val
        console.log(`当前页: ${val}`)
        this.getList()
      },
      editClick(row) {
        var status = ''
        if (row.taskStatus == '待审核' || row.taskStatus == '已完成') {
          status = '执行中'
        } else if (row.taskStatus == '执行中') {
          status = '已完成'
        }
        //cancelButtonClass: "btn-custom-cancel"
        this.$confirm(`是否将状态改为${status}`, {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          })
          .then(() => {
            movestates({
                id: row.id
              })
              .toPromise()
              .then((response) => {
                this.$notify.success({
                  title: '成功',
                  message: '状态修改成功',
                })
                this.getList()
              })
              .catch((response) => {
                // EventBus.$emit('error', this.$t('showMessage.asteriskRequired'))
              })
          })
          .catch(() => {
            return false
          })
      },
      selecttaskType(e) {
        for (var i = 0; i < this.taskTypeList.length; i++) {
          if (this.taskTypeList[i].value == e) {
            this.searchType = this.taskTypeList[i].type
          }
        }
        this.currentPage = 1,
          this.getList()
      },
      warehousechange(e){
        if(e=='全部仓库'){
          this.warehouseName=''
        }else{
          this.warehouseName=e
        }
        console.log(e)
        this.currentPage = 1,
        this.getList()
      },
      publisherchange(e){
        if(e=='全部发布者'){
          this.publisher=''
        }else{
          this.publisher=e
        }
        console.log(e)
        this.currentPage = 1,
        this.getList()
      },
      handleExamine(row) {
        this.$router.push({
          name: 'salesContractExamine',
          query: {
            id: row.id
          },
        })
      },
      // 关闭 dialog时 处理文件url 初始化upload组件
      handleCloe() {
        this.dialogViewSpareMoney = false
      },
      history(row) {
        billoperatehis({
            id: row.id
          })
          .toPromise()
          .then((response) => {
            this.historyList = response
          })
      },
      find() {
        this.currentPage = 1
        this.getList()
      },
    },
  }
</script>
<style lang="scss" scoped>
  .vertical-text-left {
    width: 62px;
    text-align: right;
  }

  .el-button--primary {
    background-color: #5878e8;
    border-color: #5878e8;
  }

  .el-button--default {
    color: #8890b1;
    border-color: #e8eaf1;
  }

  /deep/.base_header_layout .grid-content.right .find.el-button--primary {
    width: 30px;
    border-top-left-radius: 0px;
    border-bottom-left-radius: 0px;
  }

  /deep/.findValue .el-input__inner {
    border-top-right-radius: 0px;
    border-bottom-right-radius: 0px;
  }

  .completed.el-button--default {
    border-color: #5878e8;
    background-color: #f6f7fc;
    color: #5878e8;
  }

  .putstorage.el-button--default,
  .deliverystorage.el-button--default {
    border-color: #8890b1;
    background-color: #fff;
    color: #8890b1;
  }

  /deep/.el-table td,
  /deep/.el-table th.is-leaf {
    border-right: 1px solid #e9ecf7;
    text-align: center;
  }

  /deep/.el-table tr td:first-child,
  /deep/.el-table tr th.is-leaf:first-child {
    border-left: 1px solid #e9ecf7;
  }

  .el-row {
    height: 50px;
  }

  .findValue {
    // width: 0%;
    margin-left: 10px;
  }

  .search {
    margin-left: -250px;
  }

  .Value {
    width: 300px;
    margin-left: 766px;
  }

  .el-pagination {
    text-align: center;
  }

  .winseaview-main {
    background: #e8ecf6;
    box-shadow: 0px 0px 8px 0px rgba(0, 0, 0, 0.1);
  }

  .spans {
    display: table-caption;
    width: 17px;
    line-height: 19px;
  }

  //执行样式
  .executory,
  .inExecution,
  .done {
    width: 6px;
    height: 6px;
    display: inline-block;
    border-radius: 50%;
    position: relative;
    top: -1px;
    font-size: 14px;
  }

  .executory {
    background: #ff9f24;
  }

  .inExecution {
    background: #5878e8;
  }

  .done {
    background: #50cad4;
  }

  .el-select {
    width: 30%;
    margin-right: 10px;
  }

  /deep/.typeselect .el-input__inner {
    color: #8890b1;
  }

  .corles {
    color: #5878e8;
    font-size: 14px;
  }
</style>
