<template>
  <div class="app-container">
    <!--    <el-card style="max-height:500px;margin-bottom: 20px;overflow: scroll">-->
    <div class="filter-container">
      <el-input
        :size="sizeType"
        v-model="search.printBillCode"
        placeholder="施工单号"
        style="width: 200px;"
        class="filter-item"/>
      <el-select :size="sizeType" v-model="search.taskStates">
        <el-option
          v-for="item in stateOptions"
          :key="item.value"
          :label="item.label"
          :value="item.value"></el-option>
      </el-select>
      <el-date-picker
        :size="sizeType"
        v-model="searchTime"
        type="daterange"
        range-separator="-"
        start-placeholder="开始日期"
        end-placeholder="结束日期"
        value-format="yyyy-MM-dd HH:mm:ss"
        :default-time="['00:00:00', '23:59:59']">
      </el-date-picker>
      <el-button :size="sizeType" class="filter-item" type="primary" icon="el-icon-search" @click="searchData">
        搜索
      </el-button>
    </div>
    <div class="filter-container">
      <span>分配版套数:{{ userInfo.workInCount }}</span>
      <el-button
        style="margin-left: 15px"
        type="primary"
        size="mini"
        id="sys_fileHandle_refreshBtn"
        icon="el-icon-refresh"
        @click="refreshPage">刷新
      </el-button>
    </div>
    <el-table
      :size="sizeType"
      :data="tableData"
      v-loading="listLoading"
      row-key="id"
      border
      max-height="500px"
      style="margin-top: 10px;"
      ref="orderTable"
      @row-contextmenu="rowContextmenu"
      :row-class-name="tableRowClassName"
      @row-click="handleClickTableRow"
      default-expand-all>

      <el-table-column
        fixed
        width="220"
        align="center"
        label="操作">
        <template v-slot="{row}">
          <el-button
            size="mini"
            v-show="row.taskStatus === 2"
            style="margin-left: 2px"
            type="info"
            @click.stop="toVerifyTask(row)">提交审稿
          </el-button>
          <el-button
            size="mini"
            v-show="row.taskStatus === 1"
            style="margin-left: 2px"
            type="green"
            @click.stop="startTask(row)">开始
          </el-button>
          <el-button
            size="mini"
            v-show="row.taskStatus === 2"
            style="margin-left: 2px"
            type="green"
            @click.stop="completeTask(row)">完成
          </el-button>
          <el-button
            v-show="row.taskStatus ===1 || row.taskStatus ===2"
            @click.stop="backBtn(row)"
            type="primary"
            size="mini">
            退回
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        width="140"
        label="下载稿件"
      >
        <template v-slot="{row}">
          <el-button type="primary" icon="el-icon-picture-outline" @click.stop="sendPrintBillFileBtn(1,row)" title="下载PDF" plain size="mini">
          </el-button>
          <el-button type="success" icon="el-icon-folder-opened" @click.stop="sendPrintBillFileBtn(2,row)" title="打开下载目录" plain size="mini">
          </el-button>
        </template>
      </el-table-column>
      <el-table-column
        label="序号"
        fixed
        align="center"
        width="50"
        type="index">
        <template v-slot="scope">
          <span>{{ (listData.page - 1) * listData.pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="printBillCode"
        label="施工单编号"
        width="130">
        <template v-slot="{row}">
                    <span @click.stop="getPrintStep(row.idPrintBill)"
                          style="color: #409EFF;cursor: pointer" v-html="row.printBillCode"></span>
          <el-image v-if="row.importantBill == 1" :src="new_badge"></el-image>
        </template>
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="productName"
        label="产品类型"
        width="110">
        <template v-slot="{row}">
          <span @click.stop="handleDetail(row.idPrintBill)" style="color: #409EFF;cursor: pointer;"> {{
              row.productName
            }}</span>
        </template>
      </el-table-column>
      <el-table-column
        show-overflow-tooltip
        prop="customerName"
        label="客户名称"
        width="110">
        <template v-slot="{row}">
          <span>{{
              row.customerName
            }}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="breedCount"
        label="版套数"
        width="50">
      </el-table-column>

      <el-table-column
        show-overflow-tooltip
        prop="assignManName"
        label="分配人"
        width="100">
      </el-table-column>
      <el-table-column
        prop="spliceManName"
        label="拼版人">
      </el-table-column>
      <el-table-column
        label="状态">
        <template v-slot="{row}">
          <template v-if="row.pauseStatus === 0">
            <el-tag size="mini" v-if="row.taskStatus == 0">未分配</el-tag>
            <el-tag size="mini" v-else-if="row.taskStatus == 1">已分配</el-tag>
            <el-tag size="mini" v-else-if="row.taskStatus == 2">拼版中</el-tag>
            <el-tag size="mini" v-else-if="row.taskStatus == 3">待审稿</el-tag>
            <el-tag size="mini" v-else-if="row.taskStatus == 10">已完成</el-tag>
            <el-tag size="mini" v-else-if="row.taskStatus == 11">已退回</el-tag>
          </template>
          <template v-else-if="row.pauseStatus === 1">
            <el-tag size="mini" type="warning">暂停</el-tag>
          </template>
        </template>
      </el-table-column>
      <el-table-column
        prop="pauseMemo"
        label="暂停备注"
        show-overflow-tooltip
        width="150">
      </el-table-column>
      <el-table-column
        prop="backReason"
        width="100"
        show-overflow-tooltip
        label="退回原因">
      </el-table-column>
      <el-table-column
        prop="assembleBreedRequire"
        label="出版备注"
        show-overflow-tooltip
        width="100">
      </el-table-column>
      <el-table-column
        label="施工单消息"
        width="180px"
        show-overflow-tooltip
      >
        <template v-slot="{row}">
          <template v-if="row.printBillMsg">
            <el-button size="mini" icon="el-icon-plus" @click.stop="openMessage(row)"></el-button>
            <span
              style="color: #20a0ff; cursor: pointer"
              @click.stop="openMessage(row)"> {{ row.printBillMsg }}</span>
          </template>
          <template v-else>
            <el-button size="mini" icon="el-icon-plus" @click.stop="openMessage(row)"></el-button>
          </template>
        </template>
      </el-table-column>
      <el-table-column
        prop="billNote"
        label="施工单备注"
        show-overflow-tooltip
        width="150">
      </el-table-column>
      <el-table-column
        prop="deliveryDate"
        label="施工单交货期"
        width="150">
      </el-table-column>


      <el-table-column
        width="125"
        label="分配时间">
        <template v-slot="{row}">
          <span v-if="row.assignTimeLong"> {{ row.assignTimeLong | getLongTime }}</span>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="listData.total>0"
      :total="listData.total"
      :page.sync="listData.page"
      :limit.sync="listData.pageSize"
      @pagination="getList"/>
    <!--    </el-card>-->
    <div class="print-con">
      <el-row :gutter="2">
        <el-col :span="9">
          <el-card  size="mini" style="margin-top: 10px;padding: 5px;height: 200px;overflow-y: auto" v-if="printBillInfo">
            <p style="font-size: 13px;line-height: 24px;" v-html="printBillInfo"></p>
          </el-card>
        </el-col>
        <el-col :span="15">
          <el-card  size="mini" style="margin-top: 10px;padding: 5px;height: 200px;overflow-y: auto" v-if="ordreInfo">
            <p style="font-size: 13px;line-height: 24px;" v-html="ordreInfo"></p>
          </el-card>
        </el-col>
      </el-row>
    </div>
    <el-dialog title="退回" :close-on-click-modal="false" :visible.sync="backDialog" width="500px">
      <el-form label-width="80px" label-position="right">
        <el-form-item label="退回备注">
          <el-input type="textarea" v-model="backInfo.backReason"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="backDialog = false">取 消</el-button>
        <el-button type="primary" @click="checkBack">确 定</el-button>
      </div>
    </el-dialog>

    <cancledialog @tableRefresh="tableRefresh" ref="confirmDialog" :noDoubleClick="true"></cancledialog>
    <el-drawer
      title="施工单消息"
      :reverse="true"
      :visible.sync="memoDrawer"
      size="600px">
      <order-message @handleAddBreed="handleAddBreed" ref="orderMessage"></order-message>
    </el-drawer>
    <printbill-detail ref="printbillDetail"></printbill-detail>
    <print-step ref="printStep"></print-step>
    <right-menu :btnShow="btnShow" :btnList="btnList" v-if="menuVisible" @foo="foo" ref="rightmenu"
                @handleOne="handleOne" @handleAssemble="handleAssemble"></right-menu>
    <el-dialog :title="printbilTitle" :visible.sync="printbilVisible" width="500px">
      <el-form :model="printForm" label-width="50px" label-position="right">
        <el-form-item label="备注">
          <el-input type="textarea" v-model="printForm.pauseMemo"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="printbilVisible = false">取 消</el-button>
        <el-button type="primary" @click="printBtn">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="出版备注" :visible.sync="assembleVisible" width="500px">
      <el-form :model="assembleForm" label-width="90px" label-position="right">
        <el-form-item label="出版备注">
          <el-input :rows="4" type="textarea" v-model="assembleForm.assemble"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="assembleVisible = false">取 消</el-button>
        <el-button type="primary" @click="assembleBtn">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Cancledialog from '@/components/Dialog/Cancledialog'
import {getConfigInfo} from '@/api/system/config'
import new_badge from '@/assets/new_badge.gif'
import PrintbillDetail from "@/components/printbillDetail/printbillDetail";
import printStep from "@/components/printbillDetail/printStep";
import OrderMessage from '@/views/feedBack/orderMessage/orderMessage'
import rightMenu from '@/components/rightMenu/index.vue'
import {
  backExclusiveTask,
  feedbackExclusiveTask,
  getSpliceWorkState,
  querySelfExclusiveTasks,
  printBillPauseWorking,
  getPrintBillInfoStr,
  getPrintBillOrderInfoStr
} from '@/api/exclusiveSplice/dispatchOrder'
import {enforceFinishDelivery, getSendBillDetail} from "@/api/delivery/delivery";
import {
  getPrintBillAssemble,
  notePrintBillAssemble, notePrintBillAssembleByPrintBill,
  taskFeedbackPause,
  taskFeedbackStart
} from "@/api/feedBack/feedBack";

export default {
  name: 'ExclusiveSpliceProcess',
  components: {Cancledialog, PrintbillDetail, printStep, OrderMessage, rightMenu},
  data() {
    return {
      printBillInfo:"",
      ordreInfo:"",
      assembleVisible: false,
      assembleForm: {
        assemble: ""
      },
      printbilVisible: false,
      printbilTitle: "",
      printForm: {},
      btnShow: false,
      btnList: [
        {name: '暂停'},
        {name: '反馈'}
      ],
      menuVisible: false,
      memoDrawer: false,
      rowData: {},
      printBillDetail: {},
      new_badge: new_badge,
      detailVisible: false,
      sizeType: 'mini',
      userInfo: {
        workInState: '',
        workInTime: '',
        workInCount: ''
      },
      form: {
        imgSavePath: ''
      },
      search: {
        printBillCode: '',
        taskStates: '1,2,3',
        withBillMsg: 1,
        assignTimeBegin: '',
        assignTimeEnd: '',
        taskCompleteTimeBegin: '',
        taskCompleteTimeEnd: ''
      },
      searchTime: [],

      tableData: [],
      listLoading: false,
      listData: {
        total: 0,
        page: 1,
        pageSize: 20
      },

      stateOptions: [
        {
          label: '未完成',
          value: '1,2,3'
        },
        {
          label: '未开始',
          value: 1
        },
        {
          label: '拼版中',
          value: 2
        },
        {
          label: '待审稿',
          value: 3
        },
        {
          label: '已完成',
          value: 10
        }
      ],
      clickCheckId: "",
      chooseInfo: {
        idOrder: '',
        pCount: ''
      },
      distributeDialog: false,
      checkInUserList: [],
      userListLoading: false,
      userListData: {
        total: 0,
        page: 1,
        pageSize: 10
      },
      orderDetail: null,
      oldActivedId: 0,
      backDialog: false,
      backInfo: {
        id: 0,
        backReason: '',
        currentVersion: 0
      },
      drawer: false,
      stepList: [],
      timeString: '',

      dialogPdfVisible: false,
      gridDataPdf: []

    }
  },
  mounted() {
    this.getState()
    this.getList()
    // this.getConfig('FileUploadServerIp')
    // this.getConfig('OrderShareRoot')
  },
  methods: {
    sendPrintBillFileBtn(type,row){
      const _that = this;
      var userAgent = navigator.userAgent
      // console.log(_that.idOrder.toString());
      // console.log(_that.printBillDetail.billCode);
      if (userAgent.indexOf('DnyERPBrowser') > 0) {
        if(type==0){
          dyERP.sendPrintBillFile(row.idPrintBill.toString(), row.printBillCode, '0')
        }else if(type==1){
          dyERP.sendPrintBillFile(row.idPrintBill.toString(), row.printBillCode, '1')
        }else if(type==2){
          dyERP.sendPrintBillFile(row.idPrintBill.toString(), row.printBillCode, '2')
        }

      } else {
        // alert('请使用开发商提供的ERP客户端')
        _that.$message({
          message: '请使用开发商提供的ERP客户端',
          type: 'warning'
        })
      }
    },
    handleOne(row) {
      const _that = this;
      _that.rowData = row;
      console.log(row);
      if (row.pauseStatus == 1) {
        _that.printbilTitle = "确定启动？";
        _that.printForm = {
          id: row.id,
          taskStatus: row.taskStatus,
          pauseMemo: "",
          pauseStatus: 0,
          currentVersion: row.currentVersion
        }
      } else if (row.pauseStatus == 0) {
        _that.printbilTitle = "确定暂停？";
        _that.printForm = {
          id: row.id,
          taskStatus: row.taskStatus,
          pauseStatus: 1,
          pauseMemo: "",
          currentVersion: row.currentVersion
        }
      }

      _that.printbilVisible = true;
    },
    printBtn() {
      const _that = this;
      console.log(_that.printForm);

      if (!_that.printForm.pauseMemo && _that.rowData.pauseStatus === 0) {
        _that.$message.warning("备注信息不能为空");
        return
      }

      var Infos = {
        "task": JSON.stringify(_that.printForm),
      }

      printBillPauseWorking(Infos).then(response => {
        if (response.httpCode === 200) {
          _that.$message.success('操作成功')
          _that.searchData()
          _that.printForm = {}
          _that.printbilVisible = false;
        }
      }).catch(err => {
        _that.$message.error(err);
      })

    },
    handleAssemble(row) {
      const _that = this;
      _that.rowData = row;

      var Infos = {
        "idPrintBill": row.idPrintBill,
      }
      getPrintBillAssemble(Infos).then(response => {
        // console.log("taskFeedbackPause", response);
        _that.assembleVisible = true;
        _that.assembleForm.assemble = response.data

      }).catch(err => {
        _that.$message.error(err);
      })
    },
    assembleBtn() {
      const _that = this;
      if (!_that.assembleForm.assemble) {
        _that.$message("出版备注为空");
        return
      }
      var Infos = {
        "idPrintBill": _that.rowData.idPrintBill,
        "assemble": _that.assembleForm.assemble
      }
      notePrintBillAssembleByPrintBill(Infos).then(response => {
        // console.log("taskFeedbackPause", response);
        _that.assembleVisible = false;
        _that.rowData.assembleBreedRequire = _that.assembleForm.assemble;
        _that.$message.success("增加成功");


      }).catch(err => {
        _that.$message.error(err);
      })
    },
    getPrintStep(id) {
      const _that = this;

      _that.$refs.printStep.idOrder = id;
      _that.$refs.printStep.drawer = true;
      _that.$refs.printStep.getStep();
    },
    handleDetail(id) {
      const _that = this;
      _that.$refs.printbillDetail.idOrder = id;
      _that.$refs.printbillDetail.printVisible = true;
      _that.$refs.printbillDetail.fullscreenLoading = true;
      _that.$refs.printbillDetail.getDetail()
    },
    handleAddBreed(breedMsg) {
      this.memoDrawer = false;
      this.rowData.breedMsg = breedMsg;
    },
    // 施工单消息
    openMessage(row) {
      var _that = this
      _that.memoDrawer = true;
      _that.rowData = row;
      _that.$nextTick(function () {
        // console.log(_that.$refs.orderMemo);
        _that.$refs.orderMessage.idOrder = row.idPrintBill;
        _that.$refs.orderMessage.idPrint = row.idPrintBill;
        _that.$refs.orderMessage.printBillId = row.idPrintBill;
        _that.$refs.orderMessage.sMessageForm = false;
        _that.$refs.orderMessage.sMessage = "";
        _that.$refs.orderMessage.getBillMessageListByPrintBill()
      })
    },
    refreshPage() {
      this.getState()
      this.getList()
    },
    getState() {
      const _that = this
      getSpliceWorkState({}).then(res => {
        // console.log(res)
        var data = res.data
        _that.userInfo = {
          workInState: data.workInState,
          workInTime: data.workInTime,
          workInCount: data.workInCount
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    getList() {
      var _that = this
      if (_that.dispatchState == 1) {
        if (_that.searchTime == null || _that.searchTime < 0) {
          _that.search.assignTimeBegin = ''
          _that.search.assignTimeEnd = ''
        } else {
          _that.search.assignTimeBegin = _that.searchTime[0]
          _that.search.assignTimeEnd = _that.searchTime[1]
        }
      } else {
        if (_that.searchTime == null || _that.searchTime < 0) {
          _that.search.taskCompleteTimeBegin = ''
          _that.search.taskCompleteTimeEnd = ''
        } else {
          _that.search.taskCompleteTimeBegin = _that.searchTime[0]
          _that.search.taskCompleteTimeEnd = _that.searchTime[1]
        }
      }
      var params = _that.search
      _that.orderDetail = null
      var page = {
        pageIndex: _that.listData.page,
        pageSize: _that.listData.pageSize
      }
      var data = {
        'params': JSON.stringify(params),
        'page': JSON.stringify(page)
      }
      // console.log(data);
      querySelfExclusiveTasks(data).then(response => {
        // console.log(response)
        const data = response.data
        // //  组合表单数据
        data.forEach(x => {
          x.pauseStatusStr = x.pauseStatus === 0 ? '' : '已暂停'
        })
        _that.tableData = data
        _that.listData.total = response.total
        _that.listLoading = false
      }).catch(err => {
        _that.$message.error(err)
        _that.listLoading = false
      })
    },

    // 搜索
    searchData() {
      this.listData.page = 1
      this.getList()
    },

    // 刷新
    tableRefresh() {
      this.getList()
    },
    // 点击行
    // handleClickTableRow(row, event, column) {
    //   var _that = this
    //   if (row.idOrder != _that.oldActivedId) {
    //     _that.oldActivedId = row.idOrder
    //     _that.getOrderDetail(row.idOrder)
    //   }
    // },

    feedbackRow(task) {
      this.$confirm('确认反馈？')
        .then(_ => {
          const _that = this
          const data = {
            'task': task
          }
          feedbackExclusiveTask(data).then(response => {
            // console.log(response)
            if (response.httpCode === 200) {
              _that.$message.success('反馈成功')
              _that.searchData()
            }
          }).catch(err => {
            _that.$message.error(err)
          })
        })
        .catch(_ => {
        })
    },

    // 点击开始
    startTask(row) {
      const _that = this
      const task = {
        id: row.id,
        taskStatus: 2,
        currentVersion: row.currentVersion
      }
      _that.feedbackRow(task)
    },
    // 点击完成
    completeTask(row) {
      const _that = this
      const task = {
        id: row.id,
        taskStatus: 10,
        currentVersion: row.currentVersion
      }
      _that.feedbackRow(task)
    },
    // 点击提交审稿
    toVerifyTask(row) {
      const _that = this
      const task = {
        id: row.id,
        taskStatus: 3,
        currentVersion: row.currentVersion
      }
      _that.feedbackRow(task)
    },
    // 退回
    backBtn(row) {
      const _that = this
      // console.log(row);
      _that.backDialog = true
      _that.backInfo.backReason = ''
      _that.backInfo.id = row.id
      _that.backInfo.currentVersion = row.currentVersion
    },
    tableRowClassName({row, rowIndex}) {
      var _that = this;
      if (row.id == _that.clickCheckId) {
        return 'primary-row';
      }
    },
    handleClickTableRow(row, event, column) {
      const _that = this;
      if (row.rowClick == false) {
        return
      }
      _that.printBillInfo = "";
      _that.ordreInfo = "";
      _that.clickCheckId = row.id;
      _that.getPrintBillList(row.idPrintBill);
      _that.getOrderBillList(row.idPrintBill);
    },
    getPrintBillList(idBill) {
      var _that = this;
      const data = {
        'idPrintBill': idBill
      }
      getPrintBillInfoStr(data).then(response => {
        if(response.data){
          _that.printBillInfo = response.data.replace(/\r\n/g,"<br>")
        }

        for (let i = 0; i < _that.tableData.length; i++) {
          var datas = _that.tableData[i];
          if (idBill == datas.idPrintBill) {
            _that.$set(datas, 'rowClick', false);
          } else {
            _that.$set(datas, 'rowClick', true);
          }
        }
      }).catch(err => {

      })
    },
    getOrderBillList(idBill) {
      var _that = this;
      const data = {
        'idPrintBill': idBill
      }
      getPrintBillOrderInfoStr(data).then(response => {
        if(response.data){
          _that.ordreInfo = response.data.replace(/\r\n/g,"<br>");
        }

      }).catch(err => {

      })
    },
    checkBack() {
      const _that = this
      const task = {
        'task': _that.backInfo
      }
      backExclusiveTask(task).then(response => {
        // console.log(response)
        if (response.httpCode == 200) {
          _that.backDialog = false
          _that.$message({
            message: '退回成功',
            type: 'success'
          })
          _that.tableRefresh()
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },

    // 获取配置信息
    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
        }
      }).catch(err => {
        _that.$message.error(err)
      })
    },
    rowContextmenu(row, column, event) {
      const _that = this;
      _that.row = row;
      _that.clickCheckId = row.id;
      if (row.pauseStatus == 1) {
        _that.btnList[0].name = "启动";
        _that.btnShow = true;
      }
      if (row.pauseStatus == 0) {
        _that.btnList[0].name = "暂停";
        _that.btnShow = false;
      }
      _that.menuVisible = false;
      _that.menuVisible = true;

      // _that.$refs.multipleTable.toggleRowSelection(row);
      // 阻止右键默认行为
      event.preventDefault();
      _that.$nextTick(() => {
        _that.$refs.rightmenu.init(row, column, event);
        _that.$refs.rightmenu.assembleShow = true;
      })
    },
    foo() { // 取消鼠标监听事件 菜单栏
      this.menuVisible = false;
      document.removeEventListener('click', this.foo)
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .print-con .el-card__body{
  padding: 5px !important;
}
.filter-container {
  ::v-deep .el-card {
    margin-bottom: 10px;
  }
}

::v-deep .el-table .primary-row {
  background: #8cc5ff !important;
  color: #fff !important;
}
</style>
