<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select multiple size="mini" v-model="productVal" style="width: 350px" clearable filterable placeholder="产品类型"
                 value-key="id"
                 @change="productInfoChange">
        <el-option
          v-for="item in productList"
          :key="item.id"
          :label="item.productName"
          :value="item.id">
        </el-option>
      </el-select>
      <el-select multiple size="mini" v-model="teamVal" style="width: 350px" clearable filterable placeholder="业务组"
                 value-key="id"
                 @change="teamInfoChange">
        <el-option
          v-for="item in teamList"
          :key="item.id"
          :label="item.teamName+'('+item.managerUserName+')'"
          :value="item.id">
        </el-option>
      </el-select>
      <el-input :size="sizeType" v-model="search.keyWord" placeholder="关键字" style="width: 200px;" class="filter-item"/>

      <el-button :size="sizeType" class="filter-item" type="primary" icon="el-icon-search" @click="searchData">
        搜索
      </el-button>
<!--      <el-button :size="sizeType" type="green">批量下单</el-button>-->
      <div class="top-right-btn">
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button size="mini" circle icon="el-icon-refresh" @click="getList"/>
        </el-tooltip>
      </div>
    </div>
    <el-table
      :data="tableData"
      v-loading="listLoading"
      row-key="id"
      stripe
      border
      :size="sizeType"
      style="margin-top: 10px"
      @selection-change="handleSelectionChange"
      default-expand-all>
<!--      <el-table-column-->
<!--        type="selection"-->
<!--        fixed="left"-->
<!--        width="55">-->
<!--      </el-table-column>-->
      <el-table-column fixed label="操作" align="center" width="243px" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button
            title="编辑"
            v-if="row.idProduct>0"
            @click="if($store.state.app.sidebar.opened){$store.dispatch('app/toggleSideBar')};$router.push({path:'/order/editOrder/'+row.id,query:{id:row.id,orderCode:row.orderCode,editType:1,versionCode:row.versionCode,pageFrom:2}})"
            type="primary"
            icon="el-icon-edit"
            size="mini">
          </el-button>
          <el-button
            title="编辑"
            v-else-if="row.idProduct<=0"
            @click="openMaterialEdit(row)"
            type="primary"
            icon="el-icon-edit"
            size="mini">
          </el-button>
          <el-button
            type="green"
            size="mini"
            style="margin-left: 0"
            icon="el-icon-document-checked"
            @click="commitOrder(row)"
            title="提交"></el-button>
          <el-dropdown size="mini" @command="getUploadType($event,row)" trigger="click">
            <el-button size="mini" type="warning" icon="el-icon-upload"></el-button>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="1">上传文件（云）</el-dropdown-item>
<!--              <el-dropdown-item command="2">传输文件</el-dropdown-item>-->
              <el-dropdown-item command="3">关联文件</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
<!--          <el-button-->
<!--            type="warning"-->
<!--            size="mini"-->
<!--            icon="el-icon-upload"-->
<!--            @click="openFileDialog(row)"-->
<!--            title="上传文件"></el-button>-->
          <el-button size="mini" type="info" class="iconfont" title="退回" @click="openBackOrder(row)">&#xe60a;</el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="序号"
        fixed
        align="center"
        width="50"
        type="index">
        <template slot-scope="scope">
          <span>{{(listData.page - 1) *listData.pageSize + scope.$index + 1}}</span>
        </template>
      </el-table-column>
      <template v-for="column in defaultItem">
        <el-table-column
          v-if="column.id == 3"
          :prop="column.field"
          :label="column.name"
          :width="column.width"
          sortable="custom"
          fixed
          show-overflow-tooltip>
          <template slot-scope="{row}">
            <a href="javascript:;" style="color: #20a0ff" @click.stop="getOrderStep(row)">{{ row[column.field] }}
              <span v-if="row.businessKind==3" style="display: inline-block;color: red">(补{{ row.rePrintIndex}})</span>
              <el-image v-if="row.firstOrderFlag == 1" :src="new_badge"></el-image></a>
          </template>
        </el-table-column>
        <el-table-column
          v-else-if="column.id == 2"
          :prop="column.field"
          :label="column.name"
          :width="column.width"
          show-overflow-tooltip>
          <template slot-scope="{row}">
            <el-tag size="mini" v-if="row[column.field] == '待编辑'" type="info">{{ row[column.field] }}</el-tag>
            <el-tag size="mini" v-else-if="row[column.field] == '待审核'" type="success">{{ row[column.field] }}</el-tag>
            <el-tag size="mini" v-else-if="row[column.field] == '待组版'">{{ row[column.field] }}</el-tag>
            <el-tag size="mini" v-else-if="row[column.field] == '已组版'" type="danger">{{ row[column.field] }}</el-tag>
            <el-tag size="mini" v-else-if="row[column.field] == '生产中'" type="danger">{{ row[column.field] }}</el-tag>
            <el-tag size="mini" v-else-if="row[column.field] == '待入库'" type="green">{{ row[column.field] }}</el-tag>
            <el-tag size="mini" v-else-if="row[column.field] == '待发货'" >{{ row[column.field] }}</el-tag>
            <el-tag size="mini" v-else-if="row[column.field] == '已发货'" type="info">{{ row[column.field] }}</el-tag>
            <el-tag size="mini" v-else-if="row[column.field] == '文件待处理'" type="warning">{{ row[column.field] }}</el-tag>
            <el-tag v-else>{{ row[column.field] }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          v-else-if="column.id == 21"
          :prop="column.field"
          :label="column.name"
          :width="column.width">
          <template slot-scope="{row}">
            <el-tag v-if="row[column.field] == 0">初始</el-tag>
            <el-tag v-else-if="row[column.field] == 1" type="success">待审核</el-tag>
            <el-tag v-else-if="row[column.field] == 2" type="danger">待入账</el-tag>
            <el-tag v-else-if="row[column.field] == 3" type="warning">已入账</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          v-else-if="column.id == 24"
          align="center"
          header-align="center"
          :prop="column.field"
          :label="column.name"
          :width="column.width"
        >
          <template slot-scope="{row}">
            <el-tag size="mini" type="primary" v-if="row[column.field] == 0">正常业务</el-tag>
            <el-tag size="mini" type="warning" v-else-if="row[column.field]== 1">外协订单</el-tag>
            <el-tag size="mini" type="success" v-else-if="row[column.field] == 2">物料订单</el-tag>
            <el-tag size="mini" type="danger" v-else-if="row[column.field] == 3">补印订单</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          v-else-if="column.id == 6"
          header-align="center"
          :prop="column.field"
          :label="column.name"
          show-overflow-tooltip
          :width="column.width">
          <template slot-scope="{row}">
            <template v-if="row.orderMessage">
              <el-button size="mini" circle icon="el-icon-plus" @click="openMessage(row)"></el-button>
              <a href="javascript:;" style="color: #20a0ff" @click="openMessage(row)">{{row.orderMessage}}</a>
            </template>
            <template v-else>
              <el-button size="mini" circle icon="el-icon-plus" @click="openMessage(row)"></el-button>
            </template>
          </template>
        </el-table-column>
        <el-table-column
          v-else-if="column.id == 12"
          header-align="center"
          :prop="column.field"
          :label="column.name"
          :width="column.width"
        >
          <template slot-scope="{row}">
            <span v-if="row.createTime">{{ row.createTime | getTime }}</span>
          </template>
        </el-table-column>
        <el-table-column
          v-else
          :prop="column.field"
          :label="column.name"
          :width="column.width"
          show-overflow-tooltip>
        </el-table-column>
      </template>
    </el-table>
    <pagination v-show="listData.total>0" :total="listData.total" :page.sync="listData.page"
                :limit.sync="listData.pageSize" @pagination="getList"/>

    <el-drawer
      title="订单消息"
      :reverse="true"
      :visible.sync="memoDrawer"
      size="600px">
      <order-message ref="orderMessage"></order-message>
    </el-drawer>
    <el-dialog :close-on-click-modal="false" title="上传文件" :visible.sync="pluploadVisible" width="600px">
      <el-form label-width="130px" label-position="right">
        <el-form-item label="上传文件">
          <plupload
            ref="plupLoad"
            v-if="showUpload"
            :file-list="files"
            :limit="1"
            :upUrl="'apis/upload/orderFile'"
            :upType="2"
            :idOrder="upIdOrder"
            :order-code="upOrderCode"
            biz-type="trainModule"
            accept-files=".cdr,.ai,.ps,.eps,.zip,.rar,.xml,.txt,.pdf,.docx,.doc,.xlsx,.xls,.ppt,.pptx,.mp4,.mp3,.gif,.png,.jpg,.jpeg,.bmp"
            @onChange="handleFileChange"
          />
        </el-form-item>
      </el-form>
    </el-dialog>
    <el-dialog title="退回订单" :visible.sync="voidVisible" width="500px">
      <el-form label-width="80px" label-position="right">
        <el-form-item label="退回备注">
          <el-input type="textarea" v-model="sMemo"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="voidVisible = false">取 消</el-button>
        <el-button type="primary" @click="backOrderBtn">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="提示" :visible.sync="commitVisible" width="500px">
      <el-form>
        <span>订单文件已处理，请选择文件操作</span>
        <el-form-item>
          <el-radio-group v-model="commitInfo.needImageProcess">
            <el-radio :label="1">文件需要重新处理</el-radio>
            <el-radio :label="2">无需处理文件</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item>
          <el-table size="mini" :data="commitInfo.infoList" border>
            <el-table-column label="处理人" prop="userName"></el-table-column>
            <el-table-column label="处理时间" prop="dispatchTime">
              <template slot-scope="{row}">
                <span v-if="row.dispatchTime">{{row.dispatchTime |getTime}}</span>
              </template>
            </el-table-column>
            <el-table-column label="订单类型" prop="originFlag">
              <template slot-scope="{row}">
                <span v-if="row.originFlag == 0">本单</span>
                <span v-else>原单</span>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="commitVisible = false">取 消</el-button>
        <el-button type="primary" @click="commitBtn">确 定</el-button>
      </div>
    </el-dialog>
    <cancledialog @tableRefresh="tableRefresh" ref="confirmDialog"></cancledialog>
    <order-step ref="orderStep"></order-step>
    <material-detail :key="timer" ref="materialDetail"></material-detail>
  </div>

</template>

<script>
import {getOrderList, backPrintOrder, checkCompleteDispatchOrder, documentCommitOrder,getAllSaleWorkTeamList} from '@/api/order/tobeReviewed'
import orderMessage from '@/components/orderMessage/orderMessage'
import plupload from '@/components/plupload/plupload.vue'
import Cancledialog from '@/components/Dialog/Cancledialog.vue'
import {getConfigInfo} from "@/api/system/config";
import OrderStep from "@/components/orderStep/orderStep";
import MaterialDetail from "@/components/materialDetail/materialDetail";
import new_badge from '@/assets/new_badge.gif'
import {getSimpleProductInfoList} from '@/api/order/orderList.js'

const defaultItems = [
  {
    name: '订单编号', id: 3, field: 'orderCode', width: '132px'
  },
  {
    name: '产品类型', id: 1, field: 'productName', width: '130px'
  },
  {
    name: '印品名称', id: 10, field: 'orderName', width: '190px'
  },

  {
    name: '业务类型', id: 24, field: 'businessKind', width: '80'
  }, {
    name: '制单人', id: 13, field: 'createMan', width: '75'
  },
  {
    name: '制单时间', id: 12, field: 'createTime', width: '160'
  },
  {
    name: '订单状态', id: 2, field: 'stateMemo', width: ''
  },
  // {
  //   name: '应收单号', id: 4, field: 'financeCode', width: '125px'
  // },
  {
    name: '施工单号', id: 5, field: 'printBillCode', width: '125px'
  }, {
    name: '订单消息', id: 6, field: 'orderMessage', width: '170'
  }, {
    name: '客户编码', id: 7, field: 'clientCode', width: '100'
  }, {
    name: '客户名称', id: 8, field: 'clientName', width: '120'
  }, {
    name: '文件描述', id: 11, field: 'fileDescription', width: '190px'
  },
  {
    name: '订单印量', id: 14, field: 'orderQty', width: '120'
  },
  {
    name: '定金', id: 16, field: 'orderMoneyPre', width: '100'
  }, {
    name: '总金额', id: 17, field: 'orderMoneyTotal', width: '120'
  }, {
    name: '已收金额', id: 18, field: 'payMoney', width: '120'
  },
  {
    name: '平台单号', id: 20, field: 'platformOrderID', width: '220px'
  }
]
export default {
  name: 'list',
  components: {
    MaterialDetail,
    OrderStep,
    orderMessage, plupload, Cancledialog
  },
  data() {
    return {
      teamList: [],
      teamVal: [],
      productList: [],
      productVal: [],
      sizeType: 'mini',
      new_badge: new_badge,
      pluploadVisible: false,
      memoDrawer: false,
      defaultItem: Object.assign([], defaultItems), // 默认列
      orderStatus: '',
      search: {
        keyWord: '',
        orderState: '',
        idWorkTeams:'',
        idProducts:'',
      },

      tableData: [],

      listLoading: false,
      listData: {
        total: 0,
        page: 1,
        pageSize: 20
      },
      voidVisible: false,
      sMemo: '',
      versionCode: '',
      orderId: '',
      // 物料订单编辑
      timer:'',
      // 上传文件
      showUpload: true,
      files: [],
      upIdOrder: '',
      upOrderCode: '',
      confirmdialog: false,
      commitVisible: false,
      commitInfo: {
        chooseInfo: {},
        needImageProcess: 1,
        infoList: []
      }
    }
  },
  watch: {
    memoDrawer(val) {
      // console.log(val)
      if (!val) {
        this.getList()
      }
    }
  },
  mounted() {
    if (localStorage.getItem('productVal') == undefined || localStorage.getItem('productVal') == null || localStorage.getItem('productVal') == "") {
      this.productVal = [];
    } else {
      this.productVal = JSON.parse(localStorage.getItem('productVal'))
    }
    if (localStorage.getItem('teamVal') == undefined || localStorage.getItem('teamVal') == null || localStorage.getItem('teamVal') == "") {
      this.teamVal = [];
    } else {
      this.teamVal = JSON.parse(localStorage.getItem('teamVal'))
    }
    this.search.orderState = this.$route.path.split('/').slice(-1)[0]
    this.getList();
    this.getTeamInfo();
    this.getProductInfo();
    this.getConfig('FileUploadServerIp')
    this.getConfig('OrderShareRoot')
    this.getConfig('OrderUpdateWebUrl')
  },
  methods: {
    // 获取产品类型
    getProductInfo() {
      const _that = this
      var data = {}
      // console.log(data);
      getSimpleProductInfoList(data).then(response => {
        // console.log(response)
        const data = response.data
        _that.productList = data
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 获取业务组
    getTeamInfo() {
      const _that = this
      var data = {}
      // console.log(data);
      getAllSaleWorkTeamList(data).then(response => {
        // console.log(response)
        const data = response.data
        _that.teamList = data;
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    productInfoChange(val) {
      this.productVal = val;
      localStorage.setItem("productVal", JSON.stringify(this.productVal));
    },
    teamInfoChange(val) {
      this.teamVal = val;
      localStorage.setItem("teamVal", JSON.stringify(this.teamVal));
    },
    getList() {
      var _that = this;
      _that.search.idWorkTeams = "";
      _that.search.idProducts = "";
      var ids = [];
      for (let i = 0; i < _that.productVal.length; i++) {
        var datas = _that.productVal[i];
        ids.push(datas)
      }
      var idRemotes = ids.join(',');
      if (_that.productVal.length > 0) {
        _that.search.idProducts = idRemotes;
      }
      var idsTeam = [];
      for (let i = 0; i < _that.teamVal.length; i++) {
        var datasTeam = _that.teamVal[i];
        idsTeam.push(datasTeam)
      }
      var idRemotesTeam = idsTeam.join(',');
      if (_that.teamVal.length > 0) {
        _that.search.idWorkTeams = idRemotesTeam;
      }
      var params = _that.search
      var page = {
        pageIndex: _that.listData.page,
        pageSize: _that.listData.pageSize
      }
      var data = {
        'params': JSON.stringify(params),
        'page': JSON.stringify(page)
      }
      if (_that.listData.pageSize == 10) {
        _that.sizeType = 'medium'
      } else {
        _that.sizeType = 'mini'
      }
      // console.log(data);
      getOrderList(data).then(response => {
        // console.log(response)
        const data = response.data
        // //  组合表单数据
        _that.tableData = data
        _that.listData.total = response.total
        // console.log(_that.tableData)
        _that.listLoading = false
      }).catch(err => {
        _that.$message.error(err)
        _that.listLoading = false
      })
    },
    // 搜索
    searchData() {
      this.listData.page = 1
      this.getList()
    },
    handleSelectionChange(val) {
      // console.log(val)
    },
    // 获取脚印
    getOrderStep(row) {
      const _that = this
      _that.$refs.orderStep.idOrder = row.id
      _that.$refs.orderStep.getOrderStep()
    },
    // 订单消息
    openMessage(row) {
      var _that = this
      _that.memoDrawer = true
      _that.$nextTick(function() {
        // console.log(_that.$refs.orderMemo);
        _that.$refs.orderMessage.idOrder = row.id
        _that.$refs.orderMessage.getList()
      })
    },
    // 刷新变革
    tableRefresh() {
      // 刷新变革
      this.getList()
    },

    // 获取配置信息
    getConfig(key) {
      const _that = this
      const data = {
        configKey: key
      }
      // console.log(data);
      getConfigInfo(data).then(res => {
        // console.log(res)
        if (key == 'FileUploadServerIp') {
          _that.configValue1 = res.data.configValue1
        } else if (key == 'OrderShareRoot') {
          _that.configValue2 = res.data.configValue1
        } else if (key == 'OrderUpdateWebUrl') {
          _that.configValue3 = res.data.configValue1
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    // 上传文件方式选择
    getUploadType($event, row) {
      const _that = this
      var userAgent = navigator.userAgent
      if ($event == 1) {
        _that.openFileDialog(row)
      } else if ($event == 2) {
        if (_that.configValue1 == undefined) {
          _that.configValue1 = ''
        }
        if (_that.configValue2 == undefined) {
          _that.configValue2 = ''
        }
        if (userAgent.indexOf('DnyERPBrowser') > 0) {
          dyERP.sendOrderFile(row.id.toString(), row.orderCode, _that.configValue1, _that.configValue2, '0','0', '0')
        } else {
          // alert('请使用开发商提供的ERP客户端')
          this.$message({
            message: '请使用开发商提供的ERP客户端',
            type: 'warning'
          })
        }
      } else if ($event == 3) {
        if (userAgent.indexOf('DnyERPBrowser') > 0) {
          // alert('关联文件')
          dyERP.sendOrderFile(row.id.toString(), row.orderCode, _that.configValue1, _that.configValue2, '1', '0', '0')
        } else {
          // alert('请使用开发商提供的ERP客户端')
          this.$message({
            message: '请使用开发商提供的ERP客户端',
            type: 'warning'
          })
        }
      }
    },
    // 上传文件
    openFileDialog(row) {
      const _that = this
      // window.open('/#/upload?id=' + row.id + '&orderCode=' + row.orderCode + '&orderName=' + row.orderName+ '&type=1', '_blank')
      window.open(_that.configValue3 +'?id=' + row.id + '&orderCode=' + row.orderCode + '&orderName=' + row.orderName + '&type=1&idUser='+_that.$store.state.user.user.id+'&supplierCode='+_that.$store.state.user.indexInfo.supplierCode+'&dataSourceId='+_that.$store.state.user.indexInfo.dataSourceId, '_blank')
    },
    handleFileChange(fileList) {
      var _that = this
      // console.log('handleFileChange', fileList)
      _that.pluploadVisible = false
      setTimeout(() => {
        _that.tableRefresh()
      }, 1000)
    },
    // 提交订单
    commitOrder(row) {
      var _that = this
      checkCompleteDispatchOrder({idOrder:row.id}).then(res =>{
        // console.log(res);
        if(res.data.length == 0){
          var data = {
            'idOrder': row.id,
            'orderState': row.orderState,
            'versionCode': row.versionCode,
            'needImageProcess': 0
          }

          var url = '/order/v1/documentCommitOrder'
          _that.$refs.confirmDialog.updataClick(data, url)
        } else {
          _that.commitInfo.chooseInfo = row
          _that.commitVisible = true
          _that.commitInfo.infoList = res.data
        }
      })
    },
    commitBtn() {
      const _that = this
      var data = {
        'idOrder': _that.commitInfo.chooseInfo.id,
        'orderState': _that.commitInfo.chooseInfo.orderState,
        'versionCode': _that.commitInfo.chooseInfo.versionCode,
        'needImageProcess': _that.commitInfo.needImageProcess
      }
      // console.log(data);
      // return
      documentCommitOrder(data).then(res => {
        // console.log(res);
        if (res.httpCode == 200) {
          _that.commitVisible = false
          _that.$message({
            message: '提交成功',
            type: 'success'
          })
          _that.tableRefresh()
        }
      })
    },
    // 退回订单
    openBackOrder(row) {
      this.orderId = row.id
      this.orderState = row.orderState
      this.sMemo = ''
      this.voidVisible = true
      this.versionCode = row.versionCode
    },
    backOrderBtn() {
      var _that = this
      var data = {
        'id': _that.orderId,
        'sMemo': _that.sMemo,
        'orderState': _that.orderState,
        'versionCode': _that.versionCode
      }
      backPrintOrder(data).then(response => {
        // console.log(response)
        if (response.httpCode == 200) {
          _that.voidVisible = false
          _that.$message({
            message: '退回成功',
            type: 'success'
          })
          _that.tableRefresh()
        }

      }).catch(err => {
        _that.$message.error(err)
      })
    },

    // 编辑物料订单
    openMaterialEdit(row){
      const _that = this
      // _that.timer = new Date().getTime()
      _that.$nextTick(function(){
        _that.$refs.materialDetail.materialDialog = true
        _that.$refs.materialDetail.editFlag = true
        _that.$refs.materialDetail.idOrder = row.id
        _that.$refs.materialDetail.versionCode = row.versionCode
        _that.$refs.materialDetail.getOrderInfo()
      })
    },

  }
}
</script>
<style>
/*1.显示滚动条：当内容超出容器的时候，可以拖动：*/
.el-drawer__body {
  overflow: auto;
}
.stepList .el-card__body{
  padding: 10px;
}
:focus{
  outline:0;
}
</style>

<style scoped>
.filter-container {
  margin-bottom: 15px;
}
</style>
