<template>
  <div class="app-container trackingStopWarning">
    <el-form :inline="true" class="demo-form-inline">
      <el-form-item label="运单号:">
        <MultipleNumber
          style="width: 350px"
          content-width="350px"
          @getNumber="getNumber"
        />
      </el-form-item>
      <el-form-item label="创建时间:">
        <div class="block">
          <el-date-picker
            v-model="pagerDto._Range_CreateTime"
            type="daterange"
            range-separator="~"
            value-format="yyyy-MM-dd"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
          />
        </div>
      </el-form-item>
      <el-form-item label="是否停止预警:">
        <el-select v-model="pagerDto._Eq_StopObserve" style="width: 120px">
          <el-option
            v-for="item in stopObserveList"
            :key="item.label"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          icon="el-icon-search"
          size="small"
          type="primary"
          :loading="serachLadding"
          @click="searchTraceStopObservePage"
          >搜索</el-button
        >
      </el-form-item>
    </el-form>
    <div class="btns">
      <el-button
        icon="el-icon-plus"
        size="small"
        type="primary"
        @click="onOpenAddStopAlert"
      >
        添加停止预警
      </el-button>
      <el-button
        icon="el-icon-edit"
        size="small"
        type="success"
        @click="onOpenEditStopAlert"
      >
        调整勾选数据
      </el-button>
    </div>
    <el-table :data="sData" border @selection-change="handleSelectionChange">
      <el-table-column type="selection" :width="55" />
      <el-table-column label="运单号" prop="TrackingNumber" :width="310" />
      <el-table-column label="是否停止预警" prop="StopObserve" :width="110">
        <template scope="r">
          <el-tag :type="!r.row.StopObserve ? 'info' : ''">
            {{ !r.row.StopObserve ? '是' : '否' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="原因" prop="StopCause" :min-width="240" :show-overflow-tooltip="true" />
      <el-table-column label="修改时间" prop="CreateTime" :min-width="80">
        <template scope="r">
          {{ r.row.CreateTime | getDealTimeStr }}
        </template>
      </el-table-column>
      <el-table-column label="创建人" prop="CreateUserName" :min-width="80"/>
      <el-table-column label="修改时间" prop="UpdateTime" :min-width="80">
        <template scope="r">
          {{ r.row.UpdateTime | getDealTimeStr }}
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :page-sizes="[20, 50, 100, 200]"
      :current-page="pagerDto.PageIndex"
      :page-size="pagerDto.PageSize"
      background
      layout="prev, pager, next ,total ,jumper,sizes,slot "
      :total="pagerDto.total"
      @current-change="pagerSerach"
      @size-change="sizeChange"
    />
    <!-- 添加停止预警 -->
    <el-dialog
      top="10vh"
      width="780px"
      custom-class="trackingStopWarning_dialog"
      :title="getDialogTitle"
      :visible.sync="dialogTrackingStopWarning"
      :before-close="clonseTrackingStopWarning"
    >
      <div class="itemGroup">
        <el-form :model="paramsEditDto" :rules="paramsRules" ref="paramsEditDtoRef" label-width="110px">
          <el-form-item label="运单号" prop="TrackingNumberList">
            <div class="tracking">
              <el-input
                type="textarea"
                placeholder="请输入单号，每行一个"
                v-model="paramsEditDto.TrackingNumberList"
                :autosize="{ minRows: 18, maxRows: 500}"
                class="item-form"
                :readonly="!isEditState"
              />
              <span class="define-right">{{ currentRowNum }}/{{ maxRowNum }}</span>
            </div>
          </el-form-item>
          <el-form-item label="停止原因" prop="StopCause">
            <el-input
              type="textarea"
              placeholder="请输入停止原因"
              v-model="paramsEditDto.StopCause"
              :autosize="{ minRows: 3, maxRows: 6}"
              resize="none"
            />
          </el-form-item>
          <el-form-item label="是否停止预警" prop="StopObserve" v-if="!isEditState">
            <el-select v-model="paramsEditDto.StopObserve">
              <el-option
                v-for="item in stopObserveList"
                :key="item.label"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-form>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="clonseTrackingStopWarning">取 消</el-button>
        <el-button type="primary" :loading="stopObserveLoading" @click="hanleTrackingStopWarning">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import {
  _GetTraceStopObservePageResult,
  _AddTraceStopObserve,
  _ModifyTraceStopObserve
} from "@/api/tracking/trackingStopWarning";
import { _getCustomers, _getEmailType } from "@/api/baseInfo";
import MultipleNumber from "@/views/kongPai/components/multipleNumber.vue";

export default {
  name: "TrackingStopWarning",
  components: { MultipleNumber },
  filters: {
    getDealTimeStr(timerStr) {
      if (!timerStr) return ''
      return timerStr.replace('T', ' ')
    }
  },
  data() {
    return {
      serachLadding: false,
      pagerDto: {
        PageIndex: 1,
        PageSize: 20,
        total: 0,
        _Eq_Tracking: undefined,
        _Eq_StopObserve: true,
        _Range_CreateTime: null,
      },
      stopObserveList: [
        { label: "是", value: true },
        { label: "否", value: false },
      ],
      dialogTrackingStopWarning: false,
      sData: [{ StopCause: '原因' }],
      isEditState: true,
      paramsEditDto: {
        StopObserve: undefined,
        TrackingNumberList: null,
        StopCause: undefined
      },
      paramsRules: {
        TrackingNumberList: [
          { required: true, message: '请输入运单号', trigger: 'blur' },
        ],
        StopObserve: [
          { required: true, message: '请选择是否停止预警', trigger: 'change' },
        ],
        StopCause: [
          { required: true, message: '请输入停止原因', trigger: 'blur' },
        ],
      },
      currentRowNum: 0,
      maxRowNum: 500,
      stopObserveLoading: false,
      oldTrackingNumberList: []
    };
  },
  computed: {
    getDialogTitle() {
      return this.isEditState ? '添加停止预警' : '调整'
    }
  },
  watch: {
    // 监听跟踪单号
    'paramsEditDto.TrackingNumberList' (newValue, oldValue) {
      const rowNum = this.getRow()
      const maxRowNum = this.maxRowNum
      this.currentRowNum = rowNum === maxRowNum ? maxRowNum : rowNum
      if(rowNum > maxRowNum) {
        this.paramsEditDto.TrackingNumberList = oldValue
      }
    }
  },
  created() {
    this.searchTraceStopObservePage()
  },
  methods: {
    // 获取多个单号
    getNumber(numbers) {
      this.pagerDto._Eq_Tracking = numbers;
    },
    // 搜索
    searchTraceStopObservePage(pageIndex) {
      if (pageIndex && pageIndex > 0) {
        this.pagerDto.PageIndex = pageIndex;
      } else {
        this.pagerDto.PageIndex = 1;
      }
      this.serachLadding = true;
      _GetTraceStopObservePageResult(this.pagerDto)
        .then((res) => {
          this.pagerDto.total = res.TotalCount
          this.sData = res.Result
        })
        .finally(() => {
          this.serachLadding = false;
          this.oldTrackingNumberList = []
        });
    },
    pagerSerach(p) {
      this.pagerDto.PageIndex = p
      this.searchTraceStopObservePage()
    },
    sizeChange(s) {
      this.pagerDto.PageIndex = 1
      this.pagerDto.PageSize = s
      this.searchTraceStopObservePage()
    },
    // 获取当前跟踪单号文本框的行数
    getRow() {
      if(!this.paramsEditDto.TrackingNumberList) return 0
      let row = 0
      const TrackingNumberList = this.paramsEditDto.TrackingNumberList.split("\n")
      TrackingNumberList.forEach(item => {
        if (item.length === 0) {
          row += 1
        } else {
          row += Math.ceil(item.replace(/[\u0391-\uFFE5]/g,"aa").length / 50)
        }
      })
      return row
    },
    onOpenAddStopAlert() {
      this.dialogTrackingStopWarning = true
    },
    handleSelectionChange(list) {
      const newsList = list.map(item => item.TrackingNumber)
      this.oldTrackingNumberList = newsList
    },
    clonseTrackingStopWarning() {
      this.$refs.paramsEditDtoRef.resetFields();
      this.isEditState = true
      this.dialogTrackingStopWarning = false
    },
    onOpenEditStopAlert() {
      if (this.oldTrackingNumberList.length === 0) {
        this.$message({ message: '请勾选数据！', type: 'warning' })
        return
      }
      this.paramsEditDto.TrackingNumberList = this.oldTrackingNumberList.join('\n')
      this.isEditState = false
      this.dialogTrackingStopWarning = true
    },
    hanleTrackingStopWarning() {
      this.$refs.paramsEditDtoRef.validate((valid) => {
        if (valid) {
          const list = this.paramsEditDto.TrackingNumberList.split("\n")
          const TrackingNumberList = list.filter((item) => item)
          this.stopObserveLoading = true
          // 添加
          if (this.isEditState) {
            _AddTraceStopObserve({
              TrackingNumberList,
              StopCause: this.paramsEditDto.StopCause
            }).then(() => {
              this.$message({ type: 'success', message: '添加成功' })
              this.clonseTrackingStopWarning()
              this.searchTraceStopObservePage()
            }).finally(() => {
              this.stopObserveLoading = false
            })
          } else {
            // 调整
            _ModifyTraceStopObserve({
              TrackingNumberList: this.oldTrackingNumberList,
              StopCause: this.paramsEditDto.StopCause,
              StopObserve: this.paramsEditDto.StopObserve,
            }).then(() => {
              this.$message({ type: 'success', message: '调整成功' })
              this.clonseTrackingStopWarning()
              this.searchTraceStopObservePage()
            }).finally(() => {
              this.stopObserveLoading = false
            })
          }
        } else {
          return false;
        }
      });
    }
  },
};
</script>

<style scoped>
.trackingStopWarning {
  margin-top: 20px;
}
.trackingStopWarning .btns {
  margin-bottom: 10px;
}
.itemGroup{
  position: relative;
  padding-right: 26px;
}
.itemGroup .define-right {
  position: absolute;
  color: #909399;
  font-size: 14px;
  right: 15px;
  bottom: 0;
}
</style>
