<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="80px"
    >
      <el-form-item label="任务日期">
        <el-date-picker
          v-model="value1"
          label-width="180px"
          style="width: 340px"
          value-format="yyyy-MM-dd HH:mm:ss"
          type="datetimerange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :default-time="['00:00:00', '00:00:00']"
        ></el-date-picker>
      </el-form-item>
      <el-form-item
        label="任务编号"
        prop="taskCode"
      >
        <el-input
          v-model="queryParams.taskCode"
          placeholder="请输入任务编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item
        label="台车编号"
        prop="punchNo"
      >
        <el-input
          v-model="queryParams.containerCode"
          placeholder="请输入台车编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item
        label="任务类型"
        label-width="80px"
        prop="devType"
      >
        <el-select
          v-model="queryParams.taskType"
          placeholder="请选择设备类型"
          clearable
        >
          <el-option
            v-for="item in dict.type.task_type"
            :key="item.value"
            :label="item.label"
            :value="Number(item.value)"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item
        label="任务状态"
        label-width="80px"
        prop="taskStatus"
      >
        <el-select
          v-model="queryParams.taskStatus"
          placeholder="请选择任务状态"
          clearable
        >
          <el-option
            v-for="item in dict.type.task_status"
            :key="item.value"
            :label="item.label"
            :value="Number(item.value)"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <!-- <el-form-item
        label="作业方式"
        label-width="80px"
        prop="taskStatus"
      >
        <el-select
          v-model="queryParams.workStyle"
          placeholder="请选择设备类型"
          clearable
        >
          <el-option
            v-for="item in [{workStyle:'PDA作业'},{workStyle:'CTU作业'},{workStyle:'AGU作业'}] "
            :key="item.workStyle"
            :label="item.workStyle"
            :value="item.workStyle"
          >
          </el-option>
        </el-select>

      </el-form-item> -->

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置</el-button>
      </el-form-item>
    </el-form>

    <div class="layout-full">
      <heavy-table
        class="heavy-table tablem"
        style="margin-top:22px"
        highlight-current-row
        :data="cheshiList"
        :loading="loading"
        :paging="paging"
        :config="tableConfig"
        :tableProps="tableProps"
        @current-change="handleCurrentChange"
        @handleUpdate="handleUpdate"
        @handleDelete="handleDelete"
        @modifyDelete="modifyDelete"
      >
        <!-- <template v-slot:switchChange="scope">
          <el-switch
            @change="switchChange(scope.row)"
            v-model="scope.row.isActive"
            active-value="1"
            inactive-value="0"
            handleAdd
          >
          </el-switch>
        </template> -->
      </heavy-table>
    </div>

    <!-- 添加或修改区域对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="500px"
      append-to-body
    >
      <el-form
        ref="form"
        :model="form"
        :rules="rules"
        style="width: 380px;"
        label-width="95px"
      >
        <el-form-item
          label="任务起点"
          prop="fromSide"
        >
          <el-select
            v-model="form.fromSide"
            style="width: 100%;"
            placeholder="请选择"
            filterable
          >
            <el-option
              v-for="item in pointGroupNameList"
              :key="item.pointName"
              :label="item.pointName"
              :value="item.pointNo"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="任务终点"
          prop="toSide"
        >
          <el-select
            v-model="form.toSide"
            style="width: 100%;"
            placeholder="请选择"
            filterable
          >
            <el-option
              v-for="item in pointGroupNameList"
              :key="item.pointName"
              :label="item.pointName"
              :value="item.pointNo"
            />
          </el-select>
        </el-form-item>

      </el-form>
      <div
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          @click="submitForm"
        >确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getBasePointGroup, updatePoint, addPoint, queryPointList } from '@/api/wcs/base/agvPoint.js'
import { getWcsDeviceList } from '@/api/wcs/base/wcsDevice.js'
import { getDictLabel } from '@/utils/index'
import { queryTaskManagement, reissueTask, cancelTask, updateBusInDataTask } from '@/api/wcs/busFunctions/taskManagement.js'
import moment from 'moment'
export default {
  name: 'Configuration',
  dicts: ['is_use', 'task_type', 'task_status', 'order_type_dict'],
  data() {
    const _that = this
    return {
      paging: {
        page: 1, // 当前页
        size: 50, // 页面大小
        total: 0
      },
      value1: [],
      //存放设备数组
      devNameArr: [],

      tableConfig: [
        {
          label: '序号',
          prop: 'index',
          type: 'index',
          istrue: true,
          isActive: ''
        },
        {
          label: '任务单号',
          prop: 'taskCode',
          istrue: true
        },
        {
          label: '任务状态',
          prop: 'taskStatus',
          istrue: true,
          filter(row, value) {
            return getDictLabel(value, _that.dict.type.task_status)
          }
        },
        {
          label: '任务类型',
          prop: 'taskType',
          istrue: true,
          filter(row, value) {
            return getDictLabel(value, _that.dict.type.task_type)
          }
        },
        {
          label: '台车编号',
          prop: 'containerCode',
          istrue: true
        },
        {
          label: '任务起点',
          prop: 'fromSide',
          istrue: true
        },
        {
          label: '任务终点',
          prop: 'taskPath',
          istrue: true
        },
        {
          label: '异常信息',
          prop: 'exceptionMsg',
          istrue: true
        },
        {
          label: 'rcs/agv下发任务',
          prop: 'punchNo',
          istrue: true
        },
        {
          label: '订单类型',
          prop: 'dpsNoOne',
          istrue: true,
          filter(row, value) {
            return getDictLabel(value, _that.dict.type.order_type_dict)
          }
        },
        {
          label: '业务单号',
          prop: 'transId',
          istrue: true
        },
        {
          label: '任务创建时间',
          prop: 'createTime',
          istrue: true,
          sortable: true,
          width: '180px'
        },
        {
          label: '操作',
          prop: 'operating',
          istrue: true,
          type: 'button',
          width: 240,
          fixed: 'right',
          align: 'center',
          buttons: [
            {
              name: '修改任务',
              event: 'modifyDelete',
              disable(row, prop) {
                if (row.punchNo !== 'AGV') {
                  return true
                }
              }
            },
            {
              name: '重新下发',
              event: 'handleUpdate'
            },
            {
              name: '取消任务',
              event: 'handleDelete',
              disable(row, prop) {}
            }
          ]
        }
      ],
      tableProps: {
        'max-height': 700
      },

      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 区域表格数据
      pointList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      pointGroupNameList: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 50,
        groupName: null
      },
      cheshiList: [
        {
          taskCode: 'RW9209320',
          creatTime: '2023-02-26 12:05:23',
          businessCode: 'CK00000001',
          taskType: '0',
          abnormalStatus: 0,
          abnormalText: '',
          taskRoute: 'AGV-01 >> 整件Z101',
          taskStatus: '0',
          taskStyle: '2'
        },
        {
          taskCode: 'RW9209320',
          creatTime: '2023-02-26 12:05:23',
          businessCode: 'BY00000001',
          taskType: '1',
          abnormalStatus: 0,
          abnormalText: '',
          taskRoute: 'HR-01-01-01 >> U型拣选',
          taskStatus: '2',
          taskStyle: '1'
        },
        {
          taskCode: 'RW9209320',
          creatTime: '2023-02-26 12:05:23',
          businessCode: 'CK00000001',
          taskType: '2',
          abnormalStatus: 0,
          taskRoute: 'AGV-03 >> 线边01',
          taskStatus: '1',
          taskStyle: '0'
        }
      ],
      // 表单参数
      form: {},
      //所属devCode分组文字版
      groupWord: {},
      // 表单校验
      rules: {
        pointNo: [{ required: true, trigger: 'blur', message: '请输入点位编码' }],
        toSide: [{ required: true, trigger: 'blur', message: '请输入任务终点' }],
        fromSide: [{ required: true, trigger: 'blur', message: '请输入任务起点' }],
        isActive: [{ required: true, trigger: 'change', message: '启用' }],
        devCode: [{ required: true, trigger: 'change', message: '请选择设备' }]
      }
    }
  },
  created() {
    queryPointList({ pageNum: 1, pageSize: 999 }).then((res) => {
      this.pointGroupNameList = res.rows
    })
    this.getList()
  },
  computed: {},

  methods: {
    // 分页
    handleCurrentChange(val) {
      if (Object.prototype.toString.call(val) === '[object Object]') {
        this.queryParams.pageSize = val.size
        this.paging.size = val.size
        this.getList()
      } else {
        this.paging.page = val
        this.queryParams.pageNum = val
        this.getList()
      }
    },
    //修改任务
    modifyDelete(row) {
      this.open = true
      this.title = '修改任务'
      console.log(row)
      let data = {
        id: row.taskId,
        fromSide: row.fromSide,
        toSide: row.taskPath,
        taskPath: row.taskPath
      }
      this.form = data
    },
    //时间戳
    formatStringToTimestamp(formattedString) {
      // 解析格式化时间字符串为Date对象
      let date = new Date(formattedString)
      // 检查Date对象是否有效
      if (!isNaN(date.getTime())) {
        // 获取时间戳
        let timestamp = date.getTime()
        return timestamp
      } else {
        throw new Error('Invalid formatted string')
      }
    },
    /** 查询区域列表 */
    getList() {
      this.loading = true
      if (this.value1 !== null && this.value1 !== 'null' && this.value1 !== undefined) {
        this.queryParams.createTimeS = this.value1[0]
        this.queryParams.createTimeE = this.value1[1]
      } else {
        this.queryParams.createTimeS = null
        this.queryParams.createTimeE = null
      }

      queryTaskManagement(this.queryParams).then((res) => {
        res.rows = res.rows.sort((a, b) => {
          return this.formatStringToTimestamp(b['createTime']) - this.formatStringToTimestamp(a['createTime'])
        })
        this.cheshiList = res.rows
        this.paging.total = res.total
        this.loading = false
      })
      getWcsDeviceList().then((res) => {
        this.devNameArr = []
        res.data.forEach((item, index) => {
          this.devNameArr.push({ devName: item.devName, devCode: item.id })
        })
      })
    },
    compare(prop) {
      return function (a, b) {
        return b[prop] - a[prop] //降序
      }
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        groupName: null,
        equipmentStatus: null
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      ;(this.value1 = [moment().locale('zh-cn').format('yyyy-MM-DD 07:30:00'), moment().locale('zh-cn').add(1, 'days').format('yyyy-MM-DD 07:30:00')]), this.resetForm('queryForm')
      this.handleQuery()
    },
    //删除
    handleDelete(row) {
      this.$confirm('确定要取消任务吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        cancelTask({ taskId: row.taskId }).then((res) => {
          if (res.code === 200) {
            this.$message.success('取消成功')
            this.reset()
          }
        })
      })
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      // let tempRow = JSON.parse(JSON.stringify(row))
      this.reset()
      this.$confirm('确定要重新下发当前任务吗？任务下发后即可进入作业序列', '下发确认', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        reissueTask({ taskId: row.taskId }).then((res) => {
          // console.log(res)
          if (res.code === 200) {
            this.$message.success('立即下发成功')
            this.reset()
          }
        })
      })
      // let data = {
      //   id: tempRow.id,
      //   pointName: tempRow.pointName,
      //   pointNo: tempRow.pointNo,
      //   pointGroup: tempRow.groupName,
      //   // groupName: tempRow.groupName,
      //   handshakePoint: tempRow.handshakePoint,
      //   pointGroupNameList: this.pointGroupNameList,
      //   isActive: tempRow.isActive,
      //   getDevice: this.pointList.getDevice,
      //   // devName: tempRow.devName,
      //   devCode: tempRow.devName
      //   // devCode: tempRow.getDevice.id
      // }
      // this.form = data

      // this.open = true
      // this.title = '编辑'
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.form.getDevice = this.pointList.getDevice
      this.open = true

      this.title = '新增'
    },

    /** 提交按钮 */
    submitForm() {
      this.form.taskPath = this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.title === '修改任务') {
            updateBusInDataTask(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
          }
        }
      })
    }
  }
}
</script>

