<template>
  <div>
    <div v-if="!having_data" class="nodata-box">
      <img src="../images/nodata.png" />
      <p>{{ t(`flowRecord.noData`) }}</p>
    </div>
    <div v-else class="el-flow-record">
      <el-row>
        <el-col :span="24">
          <div class="status-bar" v-if="!data.hideMainFlow">{{ t(`flowRecord.number`) }}：{{ current_case_prn }}</div>
          <div class="status-bar" v-if="!data.hideMainFlow">{{ t(`flowRecord.currStatus`) }}：<span class="status">{{ current_main_flow_status }}</span></div>
          <div class="status-bar" style="float: right;color:#67BCFF; cursor: pointer;" @click="refresh_page">
            {{ t(`flowRecord.refreshData`) }}
          </div>
        </el-col>
      </el-row>
      <div class="main-flow">
        <div class="flow-title">{{ t(`flowRecord.order`) }}</div>
        <el-row v-if="!data.hideMainFlow">
          <el-col :span="24">
            <ul class="scroll flow-items-padding">
              <li v-for="item in main_flow_list" :id="item.prn" :class="main_flow_item_style(item.type)" :clickAble="getClickAble(item)" :style="item.thisNode == true ? (item.prevProcessType == '198922080024' ? 'border: 1px solid red' : item.prevProcessType == '198922138768' ? 'border: 1px solid green' : '') : ''" @click="change_sample_list(item)">
                <div v-if="item.type == 'flow'" style="position: relative">
                  <div style="position:absolute; height: 18px;right: -10px;top: -10px;color: white;line-height: 18px;">
                    <span v-if="item.dhCount && item.dhCount > 0" :title="item.dhCount" style=" background: red; min-width:18px;height: 18px;display: inline-block;border-radius:18px;font-style: 12px;">{{ item.dhCount > 99 ? '99+' : item.dhCount }}</span>
                    <span v-if="item.fgCount && item.fgCount > 0" :title="item.fgCount" style=" background: green; min-width:18px;height: 18px;display: inline-block;border-radius:18px;margin-left:2px;font-style: 12px;">{{ item.fgCount > 99 ? '99+' : item.fgCount }}</span>
                  </div>
                  <div v-if="item.flag == 1">
                    <img src="../images/icon-ywsl-high.png" v-if="item.date != '----' || item.thisNode == true" />
                    <img src="../images/icon-ywsl-gray.png" v-else />
                  </div>
                  <div v-else-if="item.flag == 2">
                    <img src="../images/icon-htps-high.png" v-if="item.date != '----' || item.thisNode == true" />
                    <img src="../images/icon-htps-gray.png" v-else />
                  </div>
                  <div v-else-if="item.flag == 7">
                    <img src="../images/icon-bgbz-high.png" v-if="item.date != '----' || item.thisNode == true" />
                    <img src="../images/icon-bgbz-gray.png" v-else />
                  </div>
                  <div v-else-if="item.flag == 8">
                    <img src="../images/icon-bgsh-high.png" v-if="item.date != '----' || item.thisNode == true" />
                    <img src="../images/icon-bgsh-gray.png" v-else />
                  </div>
                  <div v-else-if="item.flag == 9">
                    <img src="../images/icon-bgqf-high.png" v-if="item.date != '----' || item.thisNode == true" />
                    <img src="../images/icon-bgqf-gray.png" v-else />
                  </div>
                  <div v-else-if="item.flag == -1">
                    <img src="../images/icon-rwfp-high.png" v-if="item.date != '----' || item.thisNode == true" />
                    <img src="../images/icon-rwfp-gray.png" v-else />
                  </div>
                  <div v-else>
                    <img src="../images/icon-bgqf-high.png" v-if="item.date != '----' || item.thisNode == true" />
                    <img src="../images/icon-bgqf-gray.png" v-else />
                  </div>
                  <div>{{ item.name }}</div>
                  <div style="color:red;">{{ item.errorProcess }}</div>
                  <div>{{ item.date }}</div>
                  <div>{{ item.time }}</div>
                </div>
                <div v-if="item.type == 'time'" :class="main_flow_arrow_style(item.arrowStatus)">
                  <div style="height: 18px;">{{ item.timeSpan }}</div>
                </div>
              </li>

              <div style="clear: both;"></div>
            </ul>
          </el-col>
        </el-row>
        <badge :content-box-id="main_flow_records_id"></badge>
        <!-- 1折叠，0打开 -->
        <div id="main-flow-records" :show="!data.openMainFlowTable ? 1 : 0">
          <el-row>
            <el-col :span="24">
              <el-table :data="getMainFlowTranPageOrder" style="width: 100%" :header-cell-style="get_row_class">
                <el-table-column prop="operator" :label="t(`flowRecord.item.operator`)">
                </el-table-column>
                <el-table-column prop="task_node_name" :label="t(`flowRecord.item.node`)">
                </el-table-column>
                <el-table-column prop="next_task_name" :label="t(`flowRecord.item.target`)">
                </el-table-column>
                <el-table-column :label="t(`flowRecord.item.way`)">
                  <template slot-scope="scope">
                    <div :style="get_error_type_style(scope.row.process_type)">{{
                      scope.row.process_type_desc
                    }}
                    </div>
                  </template>
                </el-table-column>
                <el-table-column :label="t(`flowRecord.item.startTime`)" min-width="120">
                  <template slot-scope="scope">
                    <div class="date-time-item">{{ scope.row.date }}</div>
                    <div class="date-time-item">{{ scope.row.time }}</div>
                  </template>
                </el-table-column>
                <el-table-column prop="process_remark" width="150" :label="t(`flowRecord.item.remark`)">
                  <template slot-scope="scope">
                    <div v-if="scope.row.process_remark && isRichText(scope.row.process_remark)" @click="setRemark(scope.row.process_remark)" :style="{height: '46px',color:['198922013160', 'LZFS_ZC'].includes(scope.row.process_type) ? '' : 'red','cursor': scope.row.process_remark ? 'pointer' :''}">
                      {{ t(`flowRecord.item.detail`) }}
                    </div>
                    <div v-else>{{scope.row.process_remark}}</div>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <div class="block">
            <el-pagination @size-change="handle_mft_size_change" @current-change="handle_mft_current_change" :current-page="mft_page_index" :page-sizes="[10, 15, 20, 25, 30, 50, 100, 200, 300]" :page-size="mft_page_size" :total="getMftDataLength" layout="total, sizes, prev, pager, next, jumper">
            </el-pagination>
          </div>
        </div>
      </div>

      <childFlow :data="child_flow_data" :samples-count="samples_count" v-on:getSampleCheckListCallBack="get_sample_check_list" ref="child">
      </childFlow>
      <logtable v-if="data.printLogShow" ref="printRef" :data="print_log_flow_data"></logtable>
      <logtable v-if="data.distributionLogShow" ref="distributionRef" :data="distribution_log_flow_data"></logtable>
    </div>
    <el-dialog
          fullscreen
          :title="t(`flowRecord.remarkDetail`)"
          :visible.sync="detailMarkVisible"
          :close-on-click-modal="false"
          append-to-body
        >
        <div v-html="detailMark" style="overflow: auto;"></div>
      </el-dialog>
  </div>
</template>

<script>
import Locale from 'element-ui-qz/src/mixins/locale';
import logtable from './logtable.vue';
import childFlow from './child-flow.vue';
import badge from './badge.vue';
import ElInput from 'element-ui-qz/packages/input';
import ElButton from 'element-ui-qz/packages/button';
import ElUpload from 'element-ui-qz/packages/upload';
import ElDialog from 'element-ui-qz/packages/dialog';
import ElRow from 'element-ui-qz/packages/row';
import ElCol from 'element-ui-qz/packages/col';
import ElPagination from 'element-ui-qz/packages/pagination';
import ElTableColumn from 'element-ui-qz/packages/table-column';
import ElTable from 'element-ui-qz/packages/table';
export default {
  mixins: [Locale],
  name: 'ElFlowRecord',
  components: {
    logtable,
    childFlow,
    badge,
    ElInput,
    ElButton,
    ElUpload,
    ElDialog,
    ElCol,
    ElRow,
    ElPagination,
    ElTableColumn,
    ElTable
  },
  data: function () {
    return {
      print_log_flow_data: {
        title: this.t(`flowRecord.print.printLog`),
        orderId: this.data.orderId,
        JID: this.data.JID,
        url: "/lcgl-prj/processControl/reportPrintLogs",
        log_col: [
          {
            prop: "printDate",
            label: "打印日期",
            width: 150
          },
          {
            prop: "oprateType",
            label: "打印类型"
          },
          {
            prop: "printCopy",
            label: "打印份数"
          },
          {
            prop: "printName",
            label: "打印人"
          },
          {
            prop: "remark",
            label: "备注"
          }
        ].map(v => ({
          ...v,
          label: this.t(`flowRecord.print.${v.prop}`)
        })),
      },
      distribution_log_flow_data: {
        title: this.t(`flowRecord.release.releaseLog`),
        orderId: this.data.orderId,
        JID: this.data.JID,
        url: "/lcgl-prj/processControl/reportDistributionLogs",
        log_col: [
          {
            prop: "issueTime",
            label: "发放日期",
            width: 150
          },
          {
            prop: "orgName",
            label: "领取单位名称"
          },
          {
            prop: "issueType",
            label: "发放方法"
          },
          {
            prop: "issuerName",
            label: "发放人名称"
          },
          {
            prop: "remark",
            label: "备注"
          }
        ].map(v => ({
          ...v,
          label: this.t(`flowRecord.release.${v.prop}`)
        })),
      },
      current_case_prn: null,
      main_flow_list: [],
      main_flow_records_list: [],
      child_flow_data: {
        hide_conclusion: this.data.hide_conclusion || false,
        hide_next_task_operator: this.data.hide_next_task_operator || false,
        show_duty_sections: this.data.show_duty_sections,
        sample_data_list: null,
        sample_check_list: null
      },
      current_main_flow_status: null,
      selectedStyle: 'border:2px solid #67BCFF;',
      main_flow_item_selected_id: '',
      samples_count: null,
      main_flow_records_id: 'main-flow-records',
      having_data: true,
      mft_page_index: 1,
      mft_page_size: 10,
      child_prn_check: '',
      detailMarkVisible:false,
      detailMark:''
    };
  },
  props: {
    data: {
      type: Object, default: () => {
        return {
          prn: '',
          show_duty_sections: false,
          data_interface: '',
          JID: '',
          hide_next_task_operator: false,
          hide_conclusion: false,
          hideMainFlow: false,//是否隐藏主流程：不配置的话是不隐藏
          openMainFlowTable: false//是否展开主流程的table：不配置的话是折叠
        };
      }
    }
  },
  computed: {
    getMainFlowTranPageOrder() {
      let originalList = this.main_flow_records_list;
      let pageIndex = this.mft_page_index;
      let pageSize = this.mft_page_size;
      if (originalList !== null) {
        let list = originalList.slice((pageIndex - 1) * pageSize, pageIndex * pageSize);
        return list;
      }
    },
    getMftDataLength() {
      let originalList = this.main_flow_records_list;
      if (originalList !== null) {
        return originalList.length;
      }
    }
  },
  methods: {
    isRichText(text){
      return text && text.indexOf('<p')==0 && text.endsWith('</p>');
    },
    setRemark(html){
      this.detailMarkVisible = true;
      this.detailMark = html;
    },
    // get main flow data
    get_main_flow: function () {
      this.$http.post(this.data.data_interface + 'getListNodeByOrderNo', {
        orderNo: this.data.prn,
        JID: this.data.JID
      }, {
        emulateJSON: true,
        headers: {
          JID: this.data.JID
        }
      }).then(function (response) {
        this.create_flow_data(response.data.list, 'main');
      }, function (response) {
        console.log(response);
      });
    },
    create_flow_data: function (data, flag) {
      if (!data || !data.length) {
        if (flag === 'main') {
          this.having_data = false;
          this.main_flow_list = [];
          this.current_main_flow_status = '';
        }
        return;
      } else {
        this.having_data = true;
      }

      let tempArray = [];

      for (let i = 0; i < data.length; i++) {
        let startTimePre = '----';
        let startTimeLast = '----';
        let timeSpan = '----';
        let arrowStatus_ = 0;

        if (data[i].startTime !== undefined) {
          let startTime = new Date(data[i].startTime);
          startTimePre = this.format(startTime, 'yyyy-MM-dd');
          startTimeLast = this.format(startTime, 'hh:mm:ss');
        }
        if ((flag === 'main' && data[i].startTime !== undefined) ||
          (flag === 'main' && data[i].thisNode)) {
          this.current_main_flow_status = data[i].descp;
        }

        let temp = {
          name: data[i].descp,
          flag: data[i].disp_or,
          dhCount: data[i].dhCount,
          fgCount: data[i].fgCount,
          prevProcessType: data[i].prevProcessType,
          prn: data[i].prn,
          date: startTimePre,
          time: startTimeLast,
          type: 'flow',
          processType: data[i].processType,
          oth_id: data[i].oth_id,
          thisNode: data[i].thisNode,
          errorProcess: data[i].errorProcess
        };

        if (data[i + 1] !== undefined &&
          data[i + 1].startTime !== undefined && data[i].startTime !== undefined) {
          timeSpan = new Date(data[i + 1].startTime) - new Date(data[i].startTime);
          let tempArray = (timeSpan / 1000 / 60 / 60).toString().split('.');
          timeSpan = tempArray[0] + this.t(`flowRecord.timeH`) + Math.ceil(parseFloat('0.' + tempArray[1]) * 60) + this.t(`flowRecord.timeM`);
          if (new Date(data[i].startTime) > new Date(data[i + 1].startTime)) {
            timeSpan = '----';
          }
        }

        if (data[i].startTime !== undefined) {
          arrowStatus_ = 1;
        }

        tempArray.push(temp);
        tempArray.push({
          timeSpan: timeSpan,
          type: 'time',
          arrowStatus: arrowStatus_
        });
      }
      tempArray.pop();
      if (flag === 'main') {
        this.main_flow_list = tempArray;
      }
    },
    format: function (date, fmt) {
      let o = {
        'M+': date.getMonth() + 1, // 月份
        'd+': date.getDate(), // 日
        'h+': date.getHours(), // 小时
        'm+': date.getMinutes(), // 分
        's+': date.getSeconds(), // 秒
        'q+': Math.floor((date.getMonth() + 3) / 3), // 季度
        'S': date.getMilliseconds() // 毫秒
      };
      if (/(y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
      }
      for (var k in o) {
        if (new RegExp('(' + k + ')').test(fmt)) {
          fmt = fmt.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
        }
      }
      return fmt;
    },
    main_flow_item_style: function (val) {
      if (val === 'flow') {
        return 'flow-item';
      } else {
        return 'flow-direct';
      }
    },
    main_flow_arrow_style: function (val) {
      if (val === 0) {
        return 'arrow-line-gray';
      } else {
        return 'arrow-line-high';
      }
    },
    get_main_flow_records: function () {
      this.$http.post(this.data.data_interface + 'getTransListByOrder', {
        orderNo: this.data.prn,
        JID: this.data.JID,
        pageNo: 1,
        pageSize: 10000
      }, {
        emulateJSON: true,
        headers: {
          JID: this.data.JID
        }
      }).then(function (response) {
        let created_list = this.create_list_for_date_time(response.body.list);
        this.main_flow_records_list = created_list;
      }, function (response) {
        console.log(response);
      });
    },
    create_list_for_date_time: function (list) {
      if (list === null ||
        list.length === null) {
        return list;
      }

      let tempList = [];
      for (let i = 0; i < list.length; i++) {
        let item = list[i];
        let arr = list[i].start_time.split(' ');
        item.date = arr[0];
        item.time = arr[1];
        tempList.push(item);
      }
      return tempList;
    },
    get_sample_data: function () {
      this.$http.post(this.data.data_interface + 'getSampleListByOrder', {
        pageNo: 1,
        pageSize: 10000,
        orderNo: this.data.prn,
        JID: this.data.JID
      }, {
        emulateJSON: true,
        headers: {
          JID: this.data.JID
        }
      }).then(function (response) {
        let sample_data_list = response.body.list;
        this.child_flow_data.sample_data_list = sample_data_list;
        if (sample_data_list === null) {
          this.samples_count = 0;
        } else {
          this.samples_count = sample_data_list.length;
          if (sample_data_list.length > 0) {
            let sampleIndex = 0;
            if (this.data.sample_no) {
              sampleIndex = sample_data_list.findIndex(v => v.sample_no == this.data.sample_no) || 0;
            }
            this.get_sample_check_list(sample_data_list[sampleIndex].prn);
          }
        }
      }, function (response) {
        console.log(response);
      });
    },
    get_sample_check_list: function (prn) {
      this.child_prn_check = prn;
      this.$http.post(this.data.data_interface + 'getTestItemsBySamplePrn', {
        pageNo: 1,
        pageSize: 10000,
        samplePrn: prn,
        JID: this.data.JID
      }, {
        emulateJSON: true,
        headers: {
          JID: this.data.JID
        }
      }).then(function (response) {
        let checkList = response.data.list;
        let createdList = this.create_sample_check_list(checkList);
        this.child_flow_data.sample_check_list = createdList;
        this.$refs.child.cl_page_index = 1;
      }, function (response) {
        console.log(response);
      });
    },
    create_sample_check_list: function (list) {
      if (list === null) {
        return list;
      }
      let tempList = [];
      for (let i = 0; i < list.length; i++) {
        let item = list[i];
        item.index = i + 1;
        tempList.push(item);
      }
      return tempList;
    },
    getClickAble: function (item) {
      if ((item.type === 'flow' && item.date !== '----') ||
        (item.type === 'flow' && item.thisNode)) {
        return 0;
      } else {
        return 1;
      }
    },
    change_sample_list: function (item) {
      if (item.oth_id === '-1' || item.oth_id === 'ut_60' || item.oth_id === 'ut_50' || item.oth_id === 'ut_40') {
        return;
      }
      if ((item.type === 'flow' && item.date !== '----') ||
        (item.type === 'flow' && item.thisNode)) {
        this.$http.post(this.data.data_interface + 'getSampleListByOrder', {
          taskNodeKey: item.oth_id,
          pageNo: 1,
          pageSize: 10000,
          orderNo: this.data.prn,
          JID: this.data.JID
        }, {
          emulateJSON: true,
          headers: {
            JID: this.data.JID
          }
        }).then(function (response) {
          let sample_data_list = response.body.list;
          if (sample_data_list === null) {
            this.child_flow_data.sample_data_list = null;
            this.child_flow_data.sample_check_list = null;
          } else {
            this.child_flow_data.sample_data_list = sample_data_list;
            if (sample_data_list.length > 0) {
              this.get_sample_check_list(sample_data_list[0].prn);
            }
          }
        }, function (response) {
          console.log(response);
        });

        // handle style
        let selectedId = this.main_flow_item_selected_id;
        if (selectedId !== '') {
          let obj = document.getElementById(selectedId);
          if (obj !== null) {
            obj.setAttribute('style', '');
          }

        }
        let currentSelectedobj = document.getElementById(item.prn);
        if (currentSelectedobj !== null) {
          currentSelectedobj.setAttribute('style', this.selectedStyle);
        }

        this.main_flow_item_selected_id = item.prn;
      }
    },
    get_row_class({ row, column, rowIndex, columnIndex }) {
      if (rowIndex === 0) {
        return 'background-color:#f6f6f6';
      }
    },
    get_error_type_style(errorType) {
      let data = ['198922013160', 'LZFS_ZC'];
      return `color: ${data.includes(errorType) ? '' : 'red'}`;
    },
    refresh_page: function () {
      if (this.data.printLogShow) {
        this.$refs.printRef.page_index = 1;
      }
      if (this.data.distributionLogShow) {
        this.$refs.distributionRef.page_index = 1;
      }
      this.get_all_data();
      this.$refs.child.refresh_status();
    },
    get_all_data: function () {
      if (this.data !== undefined) {
        if (!this.data.hideMainFlow) {
          this.current_case_prn = this.data.order_no || this.data.prn;
          // reset main flow style
          let mainFlowItemSelectedId = this.main_flow_item_selected_id;
          if (mainFlowItemSelectedId !== '') {
            let currentMainFlowSelectedobj = document.getElementById(mainFlowItemSelectedId);
            if (currentMainFlowSelectedobj !== null) {
              currentMainFlowSelectedobj.setAttribute('style', '');
            }
          }
          // get data
          this.get_main_flow();
        }

        this.get_main_flow_records();
        this.get_sample_data();
        // 打印日志
        this.data.printLogShow && this.$refs.printRef.getLogArr();
        // 发放日志
        this.data.distributionLogShow && this.$refs.distributionRef.getLogArr();
      }
    },

    handle_mft_current_change(val) {
      this.mft_page_index = val;
    },
    handle_mft_size_change(val) {
      this.mft_page_size = val;
    }
  },
  watch: {
    data: function () {
      this.get_all_data();
    }
  }
};
</script>

<style lang="scss" scoped>
  /deep/.markPop_xy .el-dialog{
    min-width: 600px!important;
    width: fit-content!important;
    max-width: 1000px!important;
    overflow: auto!important;
  }
.status-bar {
  display: inline-block;
  margin-right: 20px;
}

.status-bar:last-child {
  margin-right: 0;
}

.nodata-box {
  text-align: center;
  padding: 20px 0;
  p {
    font-size: 14px;
    color: #999999;
    margin-top: 14px;
  }
}
</style>
