<template>
  <el-dialog
    v-dialogDrag
    class="dispatcher-cmd chengdou-03__systerm"
    :title="title"
    :visible.sync="show"
    width="1500px"
    :before-close="doClose"
    :z-index="2010"
    :modal="false"
    :close-on-click-modal="false"
    append-to-body
  >
    <div class="main">
      <el-row style="height: 100%;">
        <el-col :span="5" style="height: 100%;">
          <div class="left">
            <el-tabs v-model="activeTab" type="border-card" @tab-click="tabClick">
              <el-tab-pane label="操作" name="operate">
                <div class="operate-box">
                  <div class="create-cmd">
                    <!-- <span>数据库正常</span> -->
                    <div>
                      <el-select v-model="numTime" placeholder="请选择" style="width: 66px;">
                        <el-option label="24" value="24" />
                        <el-option label="12" value="12" />
                      </el-select>
                      <span>小时</span>
                    </div>
                    <span style="width: 85px; font-weight: bold; text-align: end;">{{ getSimulationTime }}</span>
                  </div>
                  <div class="create-cmd">
                    <!-- <span>通信正常</span> -->
                    <el-button type="primary" @click="refreshSearch">刷新</el-button>
                    <el-button type="primary" style="width: 100px" @click="createCmd">新建调度命令</el-button>
                  </div>
                  <div class="box-title">
                    <div class="contant-null" />
                    <div class="contant-text">缓存命令</div>
                    <div class="contant-icon" @click="active1=!active1">
                      <i v-if="active1" class="el-icon-arrow-down" />
                      <i v-else class="el-icon-arrow-up" />
                    </div>
                  </div>
                  <div v-show="active1" class="left-table1">
                    <el-table ref="table1" :data="filterDisCmdData('Cache')" border style="width: 100%" height="100" highlight-current-row @current-change="handleCurrentChange($event, 'table1')">
                      <el-table-column prop="cmdCode" label="命令号" width="80" />
                      <el-table-column prop="transitId" label="识别号" width="80" />
                      <el-table-column prop="title" label="命令标题" show-overflow-tooltip />
                      <el-table-column label="接收单位" show-overflow-tooltip width="160">
                        <template slot-scope="scope">
                          <span style="margin-left: 10px">{{ JoinDeviceNameStr(scope.row.rcvCompanies) || '' }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="sender" label="发令人" />
                      <el-table-column label="发令单位">
                        <template slot-scope="scope">
                          <span style="margin-left: 10px">{{ scope.row.sendCompany ? scope.row.sendCompany.name: '' }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="命令类型" width="100">
                        <template slot-scope="scope">
                          <span style="margin-left: 10px">{{ typeObj[scope.row.type] || '' }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="content" label="命令正文" show-overflow-tooltip />
                    </el-table>
                  </div>
                  <div class="box-title">
                    <div class="contant-null" />
                    <div class="contant-text">接受命令</div>
                    <div class="contant-icon" @click="active2=!active2">
                      <i v-if="active2" class="el-icon-arrow-down" />
                      <i v-else class="el-icon-arrow-up" />
                    </div>
                  </div>
                  <div v-show="active2" class="left-table1">
                    <el-table ref="table2" :data="filterDisCmdData('Receive')" border style="width: 100%" height="100" highlight-current-row @current-change="handleCurrentChange($event, 'table2')">
                      <el-table-column prop="cmdCode" label="命令号" width="80" />
                      <el-table-column prop="title" label="命令标题" show-overflow-tooltip />
                      <el-table-column label="接收单位" show-overflow-tooltip width="160">
                        <template slot-scope="scope">
                          <span style="margin-left: 10px">{{ JoinDeviceNameStr(scope.row.rcvCompanies) || '' }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="sendTime" label="发令时间" />
                      <el-table-column prop="sender" label="发令人" />
                      <el-table-column label="发令单位">
                        <template slot-scope="scope">
                          <span style="margin-left: 10px">{{ scope.row.sendCompany ? scope.row.sendCompany.name: '' }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="命令类型" width="100">
                        <template slot-scope="scope">
                          <span style="margin-left: 10px">{{ typeObj[scope.row.type] || '' }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="content" label="命令正文" show-overflow-tooltip />
                    </el-table>
                  </div>
                  <div class="box-title">
                    <div class="contant-null" />
                    <div class="contant-text">发送命令</div>
                    <div class="contant-icon" @click="active3=!active3">
                      <i v-if="active3" class="el-icon-arrow-down" />
                      <i v-else class="el-icon-arrow-up" />
                    </div>
                  </div>
                  <div v-show="active3" class="left-table1">
                    <el-table ref="table3" :data="filterDisCmdData('Sent')" border style="width: 100%" height="150" highlight-current-row @current-change="handleCurrentChange($event, 'table3')">
                      <el-table-column prop="cmdCode" label="命令号" width="80" />
                      <el-table-column prop="title" label="命令标题" show-overflow-tooltip />
                      <el-table-column label="接收单位" show-overflow-tooltip width="160">
                        <template slot-scope="scope">
                          <span style="margin-left: 10px">{{ JoinDeviceNameStr(scope.row.rcvCompanies) || '' }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="sendTime" label="发令时间" width="160" />
                      <el-table-column prop="sender" label="发令人" />
                      <el-table-column label="发令单位">
                        <template slot-scope="scope">
                          <span style="margin-left: 10px">{{ scope.row.sendCompany ? scope.row.sendCompany.name: '' }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="命令类型" width="100">
                        <template slot-scope="scope">
                          <span style="margin-left: 10px">{{ typeObj[scope.row.type] || '' }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="content" label="命令正文" show-overflow-tooltip />
                    </el-table>
                  </div>
                  <div class="box-title">
                    <div class="contant-null" />
                    <div class="contant-text">签收完成</div>
                    <div class="contant-icon" @click="active4=!active4">
                      <i v-if="active4" class="el-icon-arrow-down" />
                      <i v-else class="el-icon-arrow-up" />
                    </div>
                  </div>
                  <div v-show="active4" class="left-table1">
                    <el-table ref="table4" :data="filterDisCmdData('Signed')" border style="width: 100%" height="170" highlight-current-row @current-change="handleCurrentChange($event, 'table4')">
                      <el-table-column prop="cmdCode" label="命令号" width="80" />
                      <el-table-column prop="title" label="命令标题" show-overflow-tooltip />
                      <el-table-column label="接收单位" show-overflow-tooltip width="160">
                        <template slot-scope="scope">
                          <span style="margin-left: 10px">{{ JoinDeviceNameStr(scope.row.rcvCompanies) || '' }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="sendTime" label="发令时间" width="160" />
                      <el-table-column prop="sender" label="发令人" />
                      <el-table-column label="发令单位">
                        <template slot-scope="scope">
                          <span style="margin-left: 10px">{{ scope.row.sendCompany ? scope.row.sendCompany.name: '' }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column label="命令类型" width="100">
                        <template slot-scope="scope">
                          <span style="margin-left: 10px">{{ typeObj[scope.row.type] || '' }}</span>
                        </template>
                      </el-table-column>
                      <el-table-column prop="content" label="命令正文" show-overflow-tooltip />
                    </el-table>
                  </div>
                </div>
              </el-tab-pane>
              <el-tab-pane label="查询" name="search">
                <div class="search-box">
                  <div class="box-title">
                    <div class="contant-null" />
                    <div class="contant-text">查询条件</div>
                    <div class="contant-icon" @click="active5=!active5">
                      <i v-if="active1" class="el-icon-arrow-down" />
                      <i v-else class="el-icon-arrow-up" />
                    </div>
                  </div>
                  <div v-show="active5" class="search-condition">
                    <div class="condition-top">
                      <el-radio v-model="searchObj.timeType" label="1">时间范围</el-radio>
                      <el-radio v-model="searchObj.timeType" label="2">精确匹配发令时间</el-radio>
                    </div>
                    <div class="condition-border" style="padding: 5px 10px">
                      <div v-if="searchObj.timeType==1">
                        <div class="condition-row">
                          <span style="margin-right: 5px">从</span>
                          <el-date-picker v-model="searchObj.startTime" style="flex: 1" type="datetime" placeholder="选择日期时间" value-format="yyyy-MM-dd HH:mm:ss" />
                        </div>
                        <div class="condition-row">
                          <span style="margin-right: 5px">至</span>
                          <el-date-picker v-model="searchObj.endTime" style="flex: 1" type="datetime" placeholder="选择日期时间" value-format="yyyy-MM-dd HH:mm:ss" />
                        </div>
                      </div>
                      <div v-else class="condition-row">
                        <span style="margin-right: 5px">发令时间</span>
                        <el-date-picker v-model="searchObj.sendTime" style="flex: 1" type="datetime" placeholder="选择日期时间" value-format="yyyy-MM-dd HH:mm:ss" />
                      </div>
                    </div>
                    <div class="condition-row">
                      <el-checkbox v-model="searchObj.hasNumber">命令号</el-checkbox>
                      <el-input v-model="searchObj.cmdCode" />
                    </div>
                    <div class="condition-border">
                      <div class="condition-row">
                        <el-checkbox v-model="searchObj.hasCompanyOfSender">发令单位</el-checkbox>
                        <el-input v-model="searchObj.sendCompany.name" />
                      </div>
                      <div class="condition-row">
                        <el-checkbox v-model="searchObj.hasCompanyOfReceiver">受令单位</el-checkbox>
                        <el-input v-model="searchObj.companyOfReceiver" />
                      </div>
                      <div>
                        <el-checkbox v-model="searchObj.hasTitleKey">命令标题或者内容 关键字</el-checkbox>
                        <el-input v-model="searchObj.titleKey" />
                      </div>
                      <div>
                        <el-select v-model="searchObj.allSigned" placeholder="请选择">
                          <el-option
                            v-for="item in searchSignedOption"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                      </div>
                    </div>
                    <div class="condition-btn">
                      <el-button type="primary" @click="search">查询</el-button>
                      <el-button type="primary" style="width: 100px" @click="clearCondition">清除</el-button>
                    </div>
                  </div>
                  <el-table ref="table5" class="search-table" :data="searchTable" border style="width: 100%" height="100%" highlight-current-row @current-change="handleCurrentChange($event, 'table5')">
                    <el-table-column prop="cmdCode" label="命令号" width="80" />
                    <el-table-column prop="transitId" label="识别号" width="80" />
                    <el-table-column prop="title" label="命令标题" show-overflow-tooltip />
                    <el-table-column label="接收单位" show-overflow-tooltip width="160">
                      <template slot-scope="scope">
                        <span style="margin-left: 10px">{{ JoinDeviceNameStr(scope.row.rcvCompanies) || '' }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="sendTime" label="发令时间" width="160" />
                    <el-table-column prop="sender" label="发令人" />
                    <el-table-column label="发令单位">
                      <template slot-scope="scope">
                        <span style="margin-left: 10px">{{ scope.row.sendCompany ? scope.row.sendCompany.name: '' }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column label="命令类型" width="100">
                      <template slot-scope="scope">
                        <span style="margin-left: 10px">{{ typeObj[scope.row.type] || '' }}</span>
                      </template>
                    </el-table-column>
                    <el-table-column prop="content" label="命令正文" show-overflow-tooltip />
                  </el-table>
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </el-col>
        <el-col :span="15">
          <div class="middle">
            <el-tabs v-model="cmdTab" type="border-card" class="middle-padding">
              <el-tab-pane label="调度命令" name="cmd">
                <el-form ref="form" :model="command" :rules="rules" label-width="95px">
                  <el-form-item label="命令标题" prop="title">
                    <el-input v-model="command.title" />
                  </el-form-item>
                  <el-col :span="8">
                    <el-form-item label="命令号" prop="cmdCode">
                      <el-input v-model="command.cmdCode" disabled />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="中转识别号">
                      <el-input v-model="command.transitId" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="当前状态">
                      <el-input v-model="currentStatus" disabled />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="发令时间">
                      <el-date-picker v-model="command.sendTime" type="datetime" placeholder="选择日期时间" style="width: 100%;" value-format="yyyy-MM-dd HH:mm:ss" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="发令人">
                      <el-select v-model="command.sender" placeholder="请选择" style="width: 100%;" @change="senderChange">
                        <el-option
                          v-for="item in memberDataList"
                          :key="item.id"
                          :label="item.labelName"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="发令单位">
                      <el-input v-model="command.sendCompany.name" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="授权时间">
                      <el-date-picker v-model="command.authTime" type="datetime" placeholder="选择日期时间" style="width: 100%;" value-format="yyyy-MM-dd HH:mm:ss" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="值班主任">
                      <el-select v-model="command.chiefOnDuty" placeholder="请选择" style="width: 100%;">
                        <el-option
                          v-for="item in memberDataList"
                          :key="item.id"
                          :label="item.labelName"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="授权状态">
                      <el-input v-model="command.authState" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="定稿时间">
                      <el-date-picker v-model="command.finishedTime" type="datetime" placeholder="选择日期时间" style="width: 100%;" value-format="yyyy-MM-dd HH:mm:ss" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="审核人">
                      <el-select v-model="command.reviewer" placeholder="请选择" style="width: 100%;">
                        <el-option
                          v-for="item in memberDataList"
                          :key="item.id"
                          :label="item.labelName"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <div style="height: 40px; line-height: 40px; margin-left: 20px;">
                      <el-checkbox v-model="command.chiefOnDutyAuth">需值班主任授权</el-checkbox>
                    </div>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="日计划号">
                      <el-input v-model="command.dailyPlanNum" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="拟令人">
                      <el-select v-model="command.designer" placeholder="请选择" style="width: 100%;">
                        <el-option
                          v-for="item in memberDataList"
                          :key="item.id"
                          :label="item.labelName"
                          :value="item.id"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item label="命令分类">
                      <el-select v-model="command.type" placeholder="请选择" style="width: 100%;">
                        <el-option
                          v-for="item in typeOptions"
                          :key="item.value"
                          :label="item.label"
                          :value="item.value"
                        />
                      </el-select>
                    </el-form-item>
                  </el-col>
                </el-form>
              </el-tab-pane>
            </el-tabs>
            <el-tabs v-model="textTab" type="border-card">
              <el-tab-pane :label="getContentLable" name="text">
                <div class="cmd-box">
                  <div>
                    <el-input v-model="command.content" type="textarea" :rows="6" placeholder="请输入内容" maxlength="200" />
                  </div>
                </div>
              </el-tab-pane>
            </el-tabs>
            <div>
              <div class="table-title">
                <span>受令列表</span>
                <!-- <el-checkbox v-model="tableChecked">全选</el-checkbox> -->
              </div>
              <div class="table">
                <el-table ref="table" :data="getTableData" border style="width: 100%" :header-cell-class-name="cellClass" height="200" highlight-current-row @select="selectionChange" @select-all="selectionChange" @row-click="tableRowChange">
                  <el-table-column type="selection" :selectable="selectableFn" width="50" />
                  <el-table-column prop="name" label="受令单位" width="160" />
                  <el-table-column prop="copyers" label="抄送" width="120" show-overflow-tooltip />
                  <el-table-column label="签收状态">
                    <template slot-scope="scope">
                      <span style="margin-left: 10px">{{ getSignedStatus(getCurrentState(scope.row)) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="签收人">
                    <template slot-scope="scope">
                      <span style="margin-left: 10px">{{ getSignedBy(getCurrentState(scope.row)) || '' }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="签收时间" width="160">
                    <template slot-scope="scope">
                      <span style="margin-left: 10px">{{ getCurrentState(scope.row).time || '' }}</span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </div>
            <div class="midle-bottom">
              <el-button type="primary" :disabled="!allographRow" @click="allographCmd">代签</el-button>
              <el-button type="primary" :disabled="disabledSent" @click="sendCmd">下达</el-button>
              <el-button type="primary" :disabled="disabledSent" @click="saveCacheData(true)">缓存</el-button>
              <el-button type="primary" @click="doClose">关闭</el-button>
            </div>
          </div>
        </el-col>
        <el-col :span="4">
          <div class="right">
            常用词汇
          </div>
        </el-col>
      </el-row>
    </div>
  </el-dialog>
</template>
<script>
import { sendCommandNew } from '@/api/jmap/training';
import { mapState } from 'vuex';
import { parseTime } from '@/utils/index';
export default {
    name:'DispatcherCmd',
    data() {
        return {
            dialogShow: false,
            activeTab: 'operate',
            cmdTab: 'cmd',
            textTab: 'text',
            typeObj: {
                Normal: '普通调度命令',
                Construct: '施工调度命令',
                Forward: '转发调度命令',
                Request: '请求调度命令',
                LongTerm: '长效调度命令',
                ShiftScheduling: '班计划调度命令',
                Other: '其他调度命令'
            },
            signedStatusObj: {
                Cache: '缓存',
                Sent: '已发送',
                SrmReceived: '自律机接收',
                Received: '已接收',
                Signed: '已签收',
                Reject: '已拒签'
            },
            command: {
                cmdId: '',
                cmdCode: '',
                title: '',
                transitId: '',
                senderId: '',
                sendTime: '',
                sender: '',
                authTime: '',
                chiefOnDuty: '',
                chiefOnDutyAuth: false,
                authState: '',
                finishedTime: '',
                reviewer: '',
                dailyPlanNum: '',
                designer: '',
                type: 'Normal',
                content: '',
                sendCompany: {
                    id: '',
                    name: '',
                    rsCompany: true,
                    cpType: '',
                    code: '',
                    trainViaGsmR: false,
                    transStationCode: '',
                    trainNum: ''
                },
                rcvCompanies: []
                // allSigned: ''
            },
            rules: {
                title: [
                    { required: true, message: '命令标题不能为空', trigger: 'blur' },
                    { min: 1, max: 20, message: '长度在 1 到 20 个字符', trigger: 'blur' }
                ],
                cmdCode: [
                    { required: true, message: '命令号不能为空', trigger: 'blur' },
                    { min: 1, max: 7, message: '长度在 1 到 7 个字符', trigger: 'blur' }
                ]
            },
            typeTransition: {
                DISPATCHER: 'Dispatcher',
                STATION: 'Station',
                TRAIN: 'Train'
            },
            DisStationId: 'DisStation1986',
            allographRow: null,
            tableChecked: false,
            active1: true,
            active2: true,
            active3: true,
            active4: true,
            active5: true,
            numTime: 24,
            queryResData: {}, // 查询的结果数据
            // currentInfo: {},
            searchObj: {
                timeType: '1',
                startTime: '',
                endTime: '',
                sendTime: '',
                hasNumber: false,
                cmdCode: '',
                hasCompanyOfSender: false,
                sendCompany: {},
                hasCompanyOfReceiver: false,
                companyOfReceiver: '',
                hasTitleKey: false,
                titleKey: '',
                allSigned: ''
            },
            searchTable: [],
            searchSignedOption: [
                { value: '', label: '全部'},
                { value: true, label: '只显示签收完成的'},
                { value: false, label: '只显示未签收完成的'}
            ]
        };
    },
    computed: {
        ...mapState('training', [
            'memberList', 'memberData', 'simulationUserList', 'initTime'
        ]),
        ...mapState('socket', [
            'dispatchCommandState'
        ]),
        currentStatus() {
            let s = '编辑';
            const cpId = this.command.sendCompany.id;
            if (this.queryResData.companyStateMap && this.queryResData.companyStateMap[cpId]) {
                const state = this.queryResData.companyStateMap[cpId].state;
                s = this.signedStatusObj[state] ? this.signedStatusObj[state] : '编辑';
            }
            return s;
        },
        getContentLable() {
            const text = '命令正文';
            const fontLength = this.command.content.length;
            return `${text}  ${fontLength}字`;
        },
        disabledSent() {
            let s = false;
            const sentArr = ['编辑', '缓存'];
            if (!this.command.cmdCode || !sentArr.includes(this.currentStatus)) {
                s = true;
            }
            return s;
        },
        typeOptions() {
            const list = [];
            Object.keys(this.typeObj).forEach(item => {
                list.push({
                    label: this.typeObj[item],
                    value: item
                });
            });
            return list;
        },
        getSimulationTime() {
            const t = parseTime(this.initTime, '{h}:{i}:{s}');
            const tArr = t.split(':');
            let s = '  ';
            let h = tArr[0];
            if (this.numTime != 24) {
                s = '上午';
                if (h > 12) {
                    s = '下午';
                    h = h - 12;
                }
            }
            return `${s} ${h}:${tArr[1]}:${tArr[2]}`;
        },
        show() {
            return this.dialogShow;
        },
        group() {
            return this.$route.query.group;
        },
        title() {
            return '调度命令管理系统';
        },
        getTableData() {
            const mList = [];
            const filterArr = this.memberList.filter(item => {
                return item.type == 'STATION_SUPERVISOR';
            });
            filterArr.forEach(item => {
                const name = this.getDeviceName(item.deviceCode);
                mList.push({
                    code: item.deviceCode || '',
                    name: name,
                    cpType: 'Station'
                });
            });
            return mList;
        },
        memberDataList() {
            return Object.values(this.memberData);
        },
        getActiveSender() {
            const userInfo = this.memberDataList.find(item => {
                return item.userId == this.$store.state.user.id;
            });
            const activeUser = userInfo || {};
            return activeUser;
        }
    },
    watch: {
        getTableData() {
            this.allographRow = null;
        },
        getActiveSender(obj) {
            this.DisStationId = obj.deviceCode ? obj.deviceCode : 'DisStation1986';
        },
        dispatchCommandState(obj) {
            Object.values(obj.cpStateMap).forEach(item => {
                if (item.cpId) {
                    if (!this.queryResData.companyStateMap) {
                        this.queryResData.companyStateMap = {};
                    }
                    this.$set(this.queryResData.companyStateMap, item.cpId, item);
                }
            });
        }
    },
    beforeDestroy() {},
    mounted() {},
    methods:{
        cellClass(row) {
            if (row.columnIndex === 0 && this.disabledSent) {
                return 'DisableSelection';
            }
        },
        getCurrentState(row) {
            const rcList = this.command.rcvCompanies || [];
            const StateMap = this.queryResData.companyStateMap || {};
            const findRc = rcList.find(item => {
                return item.code == row.code;
            });
            let findObj = {};
            if (findRc && findRc.id && StateMap[findRc.id] && StateMap[findRc.id].state) {
                findObj = StateMap[findRc.id];
            }
            return findObj;
        },
        getSignedStatus(row) {
            let s = '';
            if (row.signedByProxy) {
                s = '代签';
            } else {
                s = this.signedStatusObj[row.state] || '';
            }
            return s;
        },
        selectableFn() {
            return !this.disabledSent;
        },
        filterDisCmdData(state) {
            const { companyStateMap = {}, disCmdMap = {}, rcvCompanyMap = {} } = this.queryResData;
            const list = [];
            if (state != 'Receive') {
                Object.values(companyStateMap).forEach(item => {
                    if (item.state == state) {
                        const findObj = this.findDisCmdObj(disCmdMap, item.cpId);
                        if (findObj) {
                            list.push(findObj);
                        }
                    }
                });
            } else {
                Object.values(rcvCompanyMap).forEach(item => {
                    const findObj = this.findDisCmdObj(disCmdMap, item.id);
                    if (findObj) {
                        list.push(findObj);
                    }
                });
            }
            return list.reverse();
        },
        findDisCmdObj(obj, val) {
            return Object.values(obj).find(item => {
                return item.sendCompany.id == val;
            });
        },
        search() {
            this.searchTable = [];
            this.searchCmd().then(res => {
                this.getSearchTable();
            });
        },
        getSearchTable() {
            const list = Object.values(this.queryResData.disCmdMap).reverse().filter(item => {
                return this.conditionFilter(item);
            });
            this.searchTable = list;
        },
        conditionFilter(item) {
            let status = true;
            if (this.searchObj.timeType == '1') {
                if (this.searchObj.startTime && new Date(this.searchObj.startTime).getTime() > new Date(item.sendTime).getTime()) {
                    status = false;
                }
                if (this.searchObj.endTime && new Date(this.searchObj.endTime).getTime() < new Date(item.sendTime).getTime()) {
                    status = false;
                }
            }
            if (this.searchObj.timeType == '2' && this.searchObj.sendTime) {
                if (this.searchObj.sendTime != item.sendTime) {
                    status = false;
                }
            }
            if (this.searchObj.hasNumber && this.searchObj.cmdCode) {
                if (this.searchObj.cmdCode != item.cmdCode) {
                    status = false;
                }
            }
            if (this.searchObj.hasCompanyOfSender && this.searchObj.sendCompany) {
                if (this.searchObj.sendCompany.name != item.sendCompany.name) {
                    status = false;
                }
            }
            if (this.searchObj.hasCompanyOfReceiver && this.searchObj.companyOfReceiver) {
                const findObj = item.rcvCompanies.find(ii => {
                    const device = this.$store.getters['map/getDeviceByCode'](ii.code);
                    const name = device ? device.name : '';
                    return name == this.searchObj.companyOfReceiver;
                });
                if (!findObj) {
                    status = false;
                }
            }
            if (this.searchObj.hasTitleKey && this.searchObj.titleKey) {
                if (!item.title.includes(this.searchObj.titleKey) && !item.content.includes(this.searchObj.titleKey)) {
                    status = false;
                }
            }
            if (this.searchObj.allSigned != '') {
                const cpId = item.sendCompany.id;
                let s = false;
                if (this.queryResData.companyStateMap && this.queryResData.companyStateMap[cpId] == 'Signed') {
                    s = true;
                }
                if (this.searchObj.allSigned != s) {
                    status = false;
                }
            }
            return status;
        },
        setCurrentRow(obj, refName) {
            const tableArr = ['table', 'table1', 'table2', 'table3', 'table4', 'table5'];
            tableArr.forEach(key => {
                if (key != refName) {
                    this.$refs[key] && this.$refs[key].setCurrentRow();
                } else {
                    this.$refs[key] && this.$refs[key].setCurrentRow(obj);
                }
            });
            this.allographRow = null;
        },
        handleCurrentChange(obj, refName) {
            if (!obj) { return; }
            // this.currentInfo = obj;
            // this.command = {...obj};
            Object.keys(this.command).forEach(key => {
                this.command[key] = obj[key] || '';
            });
            this.setCurrentRow(obj, refName);
            this.$refs.table.clearSelection();
            const infoList = this.command.rcvCompanies || [];
            infoList.forEach(item => {
                const findObj = this.getTableData.find(ii => {
                    return ii.code == item.code;
                });
                findObj && this.$refs.table.toggleRowSelection(findObj, true);
            });
        },
        getSignedBy(info) {
            const signedInfo = this.memberData[info.operatorId];
            let name = '';
            if (signedInfo) {
                name = signedInfo.labelName;
            }
            return name;
        },
        getDeviceName(receiverId) {
            let name = '';
            if (receiverId) {
                const device = this.$store.getters['map/getDeviceByCode'](receiverId);
                name = device ? device.name : '';
            }
            return name;
        },
        JoinDeviceNameStr(devCodeArr) {
            let name = '';
            const nameArr = [];
            devCodeArr.forEach(ii => {
                const device = this.$store.getters['map/getDeviceByCode'](ii.code);
                nameArr.push(device ? device.name : '');
            });
            name = nameArr.join(',');
            return name;
        },
        refreshSearch() {
            console.log('刷新');
            this.searchCmd();
        },
        clearCondition() {
            this.searchTable = [];
            this.searchObj = {
                timeType: '1',
                startTime: '',
                endTime: '',
                sendTime: '',
                hasNumber: false,
                cmdCode: '',
                hasCompanyOfSender: false,
                sendCompany: {},
                hasCompanyOfReceiver: false,
                companyOfReceiver: '',
                hasTitleKey: false,
                titleKey: '',
                allSigned: ''
            };
        },
        createCmd() {
            const obj = this.resetData();
            const findDiff = Object.keys(obj).find(key => {
                if (key == 'sendCompany') {
                    return obj[key].name != this.command[key].name;
                } else if (key == 'rcvCompanies') {
                    return this.command[key].length;
                } else {
                    return obj[key] != this.command[key];
                }
            });
            new Promise((resolve, reject) => {
                if (findDiff) {
                    this.$confirm('当前调度命令已经被编辑修改过了，你要放弃所有的修改吗？', '操作提示', {
                        confirmButtonText: '是',
                        cancelButtonText: '否'
                    }).then(() => {
                        resolve();
                    }).catch(() => {
                        reject();
                    });
                } else {
                    resolve();
                }
            }).then(() => {
                this.initData();
                this.getSenderName();
                sendCommandNew(this.group, 'CTC_NEW_DIS_COMMAND', {}).then((res) => {
                    console.log(res, '---新建调度命令号');
                    this.command.cmdCode = res.data.cmdCode;
                    this.command.cmdId = res.data.cmdId;
                }).catch(error => {
                    this.$messageBox('新建调度命令号失败：' + error.message);
                });
            }).catch(() => {
                console.log('取消新建调度命令!');
            });
        },
        resetData() {
            const data = this.getSendCompanyData(this.$store.state.user.id);
            return {
                cmdId: '',
                cmdCode: '',
                title: '',
                transitId: '',
                senderId: '',
                sendTime: '',
                sender: this.command.sender,
                authTime: '',
                chiefOnDuty: '',
                chiefOnDutyAuth: false,
                authState: '',
                finishedTime: '',
                reviewer: '',
                dailyPlanNum: '',
                designer: '',
                type: 'Normal',
                content: '',
                sendCompany: {
                    id: '',
                    name: data.name || '',
                    rsCompany: true,
                    cpType: data.type || '',
                    code: data.code || '',
                    trainViaGsmR: false,
                    transStationCode: '',
                    trainNum: ''
                },
                rcvCompanies: []
            };
        },
        initData() {
            this.command = {
                ...this.resetData()
            };
            // this.currentInfo = {};
            this.$refs.table && this.$refs.table.clearSelection();
            this.$refs.form && this.$refs.form.resetFields();
            this.setCurrentRow();
        },
        getSendCompanyData(memberId) {
            const obj = this.memberDataList.find(item => {
                return item.userId == memberId;
            });
            let data = {
                type: '',
                name: '',
                code: ''
            };
            if (obj) {
                data = {
                    name: obj.label,
                    rsCompany: false,
                    cpType: this.typeTransition[obj.type] || obj.type,
                    code: obj.deviceCode || this.DisStationId
                };
            }
            return data;
        },
        senderChange(memberId) {
            const data = this.getSendCompanyData(memberId);
            this.$set(this.command, 'sendCompany', data);
        },
        getSenderName() {
            const activeUser = this.memberDataList.find(item => {
                return item.userId == this.$store.state.user.id;
            });
            if (activeUser) {
                // this.command.senderId = activeUser.id;
                this.command.sender = activeUser.labelName;
                this.senderChange(activeUser.userId);
            }
        },
        doShow() {
            this.initData();
            this.searchCmd();
            this.getSenderName();
            this.dialogShow = true;
        },
        doClose() {
            this.dialogShow = false;
        },
        tabClick() {
            console.log('tabClick');
        },
        selectionChange(selection) {
            const arr = [];
            selection.forEach(item => {
                arr.push({
                    name: item.name,
                    rsCompany: true,
                    cpType: item.cpType,
                    code: item.code,
                    ...item
                });
            });
            this.command.rcvCompanies = arr;
        },
        getCompanyIdList(sum) {
            return new Promise((resolve, reject) => {
                sendCommandNew(this.group, 'CTC_NEW_COMPANY_DIS_COMMAND', {sum: sum}).then(suc => {
                    resolve(suc.data);
                }).catch(err => {
                    reject(err.message);
                });
            });
        },
        saveCacheData(showMsg) {
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    if (!this.command.content) {
                        this.$messageBox('请选择填写命令正文');
                        return;
                    }
                    if (!this.command.rcvCompanies.length) {
                        this.$messageBox('请选择受令单位');
                        return;
                    }
                    this.cacheCmd(showMsg).then(suc => {
                        this.searchCmd();
                        this.initData();
                    });
                }
            });
        },
        cacheCmd(showMsg) {
            console.log('缓存', this.command);
            return new Promise(async(resolve, reject) => {
                const data = JSON.parse(JSON.stringify(this.command));
                const idList = await this.getCompanyIdList(data.rcvCompanies.length + 1);
                data.rcvCompanies.forEach((item, index) => {
                    item.id = idList[index];
                });
                data.sendCompany.id = idList[idList.length - 1];
                sendCommandNew(this.group, 'CTC_SAVE_DIS_COMMAND', data).then((res) => {
                    showMsg && this.$message.success('缓存调度命令成功！');
                    resolve();
                }).catch(error => {
                    showMsg && this.$messageBox('缓存调度命令失败：' + error.message);
                    reject(error.message);
                });
            });
        },
        tableRowChange(row, column, event) {
            const sArr = [undefined, 'Sent', 'Received', 'SrmReceived'];
            const findCode = this.command.rcvCompanies.find(item => {
                return item.code == row.code;
            });
            if (this.currentStatus == '已发送' && findCode && sArr.includes(row.state)) {
                this.allographRow = row;
            } else {
                this.allographRow = null;
            }
        },
        allographCmd() {
            if (!this.allographRow) { return; }
            const test = `当前操作者：【${this.getActiveSender.labelName || ''}】，为【${this.command.cmdCode}】号调度命令的受令单位【${this.allographRow.name}】`;
            const messageData = [test];
            const h = this.$createElement;
            messageData.push(h('p', null, '进行代签操作前，请您与受令单位进行联络确认。'));
            messageData.push(h('p', null, '您确定要进行代签操作吗？'));
            this.$confirm('提示', {
                title: '代签操作提示',
                message: h('div', null, messageData),
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                console.log('代签');
                sendCommandNew(this.group, 'CTC_SIGN_DIS_COMMAND', {cmdId: this.command.cmdId, rcId: this.allographRow.cpId, proxySign: true}).then((res) => {
                    console.log(res, '---res');
                    this.$message.success('代签成功！');
                    this.searchCmd();
                    this.initData();
                }).catch(error => {
                    this.$messageBox('代签令失败：' + error.message);
                });
            }).catch(() => {
                console.log('取消代签');
            });
        },
        sendCmd() {
            const test = `【${this.command.cmdCode}】号调度命令下达到以下受令人：`;
            const messageData = [test];
            const h = this.$createElement;
            this.command.rcvCompanies.forEach((item, index) => {
                const msg = `${index + 1}. ${item.name || ''}`;
                messageData.push(h('p', null, msg));
            });
            this.$confirm('提示', {
                title: '操作提示',
                message: h('div', null, messageData),
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$refs['form'].validate((valid) => {
                    if (valid) {
                        if (!this.command.content) {
                            this.$messageBox('请选择填写命令正文');
                            return;
                        }
                        if (!this.command.rcvCompanies.length) {
                            this.$messageBox('请选择受令单位');
                            return;
                        }
                        this.cacheCmd().then(suc => {
                            sendCommandNew(this.group, 'CTC_SEND_DIS_COMMAND', {cmdId: this.command.cmdId}).then((res) => {
                                console.log(res, '---res');
                                this.$message.success('发送调度命令成功！');
                                this.searchCmd();
                                this.initData();
                            }).catch(error => {
                                this.$messageBox('发送调度命令失败：' + error.message);
                            });
                        }).catch(err => {
                            console.log('缓存调度命令失败', err);
                        });
                    }
                });
            });
        },
        searchCmd() {
            return new Promise((resolve, reject) => {
                sendCommandNew(this.group, 'CTC_QUERY_DIS_COMMAND', {holderType: 'Dispatcher', holderCode: this.DisStationId}).then((res) => {
                    console.log(res, '---res----');
                    this.queryResData = res.data || {};
                    resolve();
                }).catch(error => {
                    this.$messageBox('查询调度命令失败：' + error.message);
                    reject(error.message);
                });
            });
        }
    }

};
</script>
<style lang="scss" scoped>
// .dispatcher-cmd{
// }
.main {
	height: 100%;
	.left {
		height: 100%;
		.operate-box {
			overflow-y: auto;
		}
		.create-cmd {
			height: 30px;
			display: flex;
			justify-content: flex-end;
			align-items: center;
		}
		.box-title {
			height: 28px;
			display: flex;
			justify-content: center;
			align-items: center;
			background: #B3B2C2;
			.contant-null, .contant-icon {
				width: 20px;
				display: flex;
				justify-content: center;
			}
			.contant-icon:hover {
				cursor: pointer;
			}
			.contant-text {
				display: flex;
				justify-content: center;
				flex: 1;
				color: blue;
			}
		}
		.search-box {
			height: 720px;
			display: flex;
			flex-direction: column;
			justify-content: center;
			.search-condition {
				padding: 5px;
				.condition-top {
					padding: 5px;
				}
				.condition-btn {
					padding: 10px;
					text-align: center;
				}
			}
			.search-table {
				flex: 1;
			}
			.condition-border {
				margin: 10px 0;
				padding: 5px;
				border: 1px solid #92ACD7;
				div {
					margin: 5px 0;
				}
			}
			.condition-row {
				display: flex;
				justify-content: space-between;
				align-items: center;
				height: 32px;
				line-height: 32px;
			}
			.el-checkbox {
				margin-right: 5px;
			}
		}
	}
	/deep/ .el-tabs__item {
		height: 30px !important;
		line-height: 30px !important;
	}
	/deep/ .el-table .DisableSelection .cell .el-checkbox__inner{
        display: none;
        position: relative;
      }
      .el-table .DisableSelection .cell:before{
        content: "";
        position: absolute;
      }
	.middle, .left {
		.middle-padding {
			padding-right: 5px;
		}
		/deep/ .el-form-item {
			margin-bottom: 0px;
			.el-form-item__error {
				top: 30px;
			}
		}
		.el-input {
			/deep/ .el-input__icon {
				line-height: 22px;
			}
		}
		.midle-bottom {
			height: 40px;
			display: flex;
			justify-content: center;
			align-items: center;
		}
	}
}
</style>
<style>
.dispatcher-cmd .el-dialog .el-dialog__body {
	padding: 5px !important;
}
.dispatcher-cmd .el-dialog {
	margin-top: 8vh !important;
}
.dispatcher-cmd .el-tabs--border-card>.el-tabs__content {
	padding: 5px !important;
}
</style>
