<template>
  <div class="ele-body">
    <el-card shadow="never">
      <!-- <patrolSearch @search="search"></patrolSearch> -->
      <seek-page
        :seekList="seekList"
        @search="search"
        :maxLength="4"
        style="margin-bottom: 15px"
      ></seek-page>
      <ele-pro-table
        ref="table"
        row-key="id"
        :columns="columns"
        :datasource="datasource"
        @columns-change="handleColumnChange"
        :cache-key="cacheKeyUrl"
        height="calc(100vh - 420px)"
        :page-size="defPageSize"
      >
        <template v-slot:toolbar>
          <el-button
            type="primary"
            size="mini"
            icon="el-icon-plus"
            @click="openEdit('add')"
            >新建临时计划</el-button
          >
        </template>

        <template v-slot:code="{ row }">
          <el-link
            type="primary"
            :underline="false"
            @click="openEdit('detail', row)"
          >
            {{ row.code }}
          </el-link>
        </template>

        <template v-slot:action="{ row }">
          <el-link
            type="primary"
            :underline="false"
            @click="openEdit('edit', row)"
            v-if="row.status != 2 && row.status != 3"
          >
            修改
          </el-link>

          <el-link
            type="primary"
            :underline="false"
            v-if="row.dispatchType == 1 || (row.status != 2 && row.status != 3)"
            @click="openEdit('dispatch', row)"
          >
            派单
          </el-link>
          <el-link
            type="primary"
            :underline="false"
            v-if="row.dispatchType == 1"
            @click="openEdit('dispatch', row, 'dispatchAll')"
          >
            批量派单
          </el-link>

          <el-link
            type="primary"
            :underline="false"
            v-if="row.status == 2"
            @click="handleRevoke(row)"
          >
            撤回
          </el-link>

          <el-popconfirm
            class="ele-action"
            title="确定要删除此条数据吗？"
            @confirm="deleteRow(row.id)"
            v-if="row.status != 2 && row.status != 3"
          >
            <template v-slot:reference>
              <el-link type="danger" :underline="false"> 删除 </el-link>
            </template>
          </el-popconfirm>
        </template>
      </ele-pro-table>
    </el-card>

    <programRulesDialog
      ref="programRulesDialogRef"
      @reload="reload"
      :pageName="pageName"
      :planType="planTypeList[pageName]"
    ></programRulesDialog>

    <batchRevokeDialog
      ref="batchRevokeDialogRef"
      :pageName="pageName"
      :planType="planTypeList[pageName]"
      @refresh="reload"
    ></batchRevokeDialog>
  </div>
</template>

<script>
  import dictMixins from '@/mixins/dictMixins';
  import tableColumnsMixin from '@/mixins/tableColumnsMixin';
  import {
    recordrulesplanPage,
    recordrulesplanDelete,
    recordrulesplanRevoke
  } from '@/api/recordRules/index';
  import programRulesDialog from './programRulesDialog.vue';
  import batchRevokeDialog from './batchRevokeDialog.vue';
  import { getteampage } from '@/api/main/index.js';
  import { getFactoryarea } from '@/api/factoryModel/index';

  export default {
    mixins: [dictMixins, tableColumnsMixin],
    components: {
      programRulesDialog,
      batchRevokeDialog
    },
    props: {
      pageName: {
        type: String,
        default: 'productionRecords'
      }
    },
    data() {
      return {
        planTypeList: {
          productionRecords: 2,
          steamInjectionInspectionRecord: 3,
          solidWasteRecord: 4,
          qualityTestRecords: 5,
          boilerOperationRecord: 6,
          QualityInspection: 7,
          HaulSlag: 8,
          TransportAsh: 9
        },

        columns: [
          {
            columnKey: 'index',
            label: '序号',
            type: 'index',
            width: 55,
            align: 'center',
            showOverflowTooltip: true,
            fixed: 'left'
          },
          {
            prop: 'code',
            label: '计划单号',
            align: 'center',
            minWidth: 160,
            slot: 'code'
          },
          {
            prop: 'name',
            label: '计划名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'ruleName',
            label: '记录规则名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'productLineName',
            label: '场站名称',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'teamName',
            label: '班组',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: '',
            label: '部门',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110,
            formatter: (row) => {
              return [
                ...new Set(
                  (row.executeUsers || [])
                    .map((i) => i.groupName)
                    .filter((i) => i)
                )
              ].join(',');
            }
          },
          {
            prop: '',
            label: '负责人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110,
            formatter: (row) => {
              return row.executeUsers.map((i) => i.userName).join(',');
            }
          },

          {
            prop: 'workshopName',

            label: '记录对象',
            align: 'center',
            showOverflowTooltip: true,
            formatter: (row) => {
              console.log(row);
              if (row.associatedObject == 1) {
                return row.workshopName;
              } else {
                return row.deviceName;
              }
            },
            minWidth: 110
          },
          {
            prop: 'dispatchType',
            label: '派单类型',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110,
            formatter: (row) => {
              return row.dispatchType ? '多次' : '单次';
            }
          },
          {
            prop: 'status',
            label: '状态',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110,
            formatter: (row) => {
              //  0-未派单，2-执行中，3-已完成，4-已撤回
              const statusMap = {
                0: '未派单',
                2: '执行中',
                3: '已完成',
                4: '已撤回'
              };
              return statusMap[row.status] || '';
            }
          },
          {
            prop: 'createUserName',
            label: '创建人',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            prop: 'createTime',
            label: '创建时间',
            align: 'center',
            showOverflowTooltip: true,
            minWidth: 110
          },
          {
            columnKey: 'action',
            label: '操作',
            width: 220,
            align: 'center',
            resizable: false,
            fixed: 'right',
            slot: 'action',
            showOverflowTooltip: true
          }
        ],
        cacheKeyUrl: `pcs-2511241029-${this.pageName + ''}-plan`,
        teamList: [],
        productLineList: []
      };
    },
    computed: {
      seekList() {
        return [
          {
            label: '关键字',
            value: 'keyword',
            type: 'input',
            width: '280px',
            placeholder: '计划单号，计划名称，记录规则名称'
          },
          {
            label: '场站',
            value: 'productLineId',
            type: 'select',
            planList: this.productLineList,
            placeholder: '请选择'
          },
          {
            label: '班组',
            value: 'teamId',
            type: 'select',
            planList: this.teamList,
            placeholder: '请选择'
          },
          {
            label: '状态',
            value: 'status',
            type: 'select',
            placeholder: '请输入',
            planList: [
              { value: 0, label: '未派单' },
              { value: 2, label: '执行中' },
              { value: 3, label: '已完成' },
              { value: 4, label: '已撤回' }
            ]
          },
          {
            label: '创建时间：',
            value: 'createTime',
            type: 'date',
            dateType: 'datetimerange',
            placeholder: '',
            width: 380,
            valueAr: ['createTimeStart', 'createTimeEnd']
          }
        ];
      }
    },
    created() {
      this.requestDict('记录规则类型');
      getteampage({
        pageNum: 1,
        size: -1
      }).then((res) => {
        this.teamList =
          res.list.map((item) => {
            return {
              value: item.id,

              label: item.name
            };
          }) || [];
      });
      getFactoryarea({
        pageNum: 1,
        size: 999,
        type: 4
      }).then((res) => {
        console.log(res, 'res');
        this.productLineList =
          res.list.map((item) => {
            return {
              value: item.id,

              label: item.name
            };
          }) || [];
      });
    },
    methods: {
      // 刷新表格
      reload(where = {}) {
        this.$refs.table.reload({
          where
        });
      },
      /* 表格数据源 */
      datasource({ page, limit, where, order }) {
        // 参数
        const body = {
          ...where,
          ...order,
          pageNum: page,
          size: limit,
          planType: this.planTypeList[this.pageName]
        };
        return recordrulesplanPage(body);
      },
      search(where) {
        console.log('where', where);
        if (where.time) {
          where.createTimeStart = where.time[0];
          where.createTimeEnd = where.time[1];
          where.time = null;
        }
        this.reload(where);
      },
      openEdit(type, row = null, dispatchType) {
        this.$refs.programRulesDialogRef.open(
          type,
          row,
          this.getDictCode(
            '记录规则类型',
            this.pageName == 'productionRecords'
              ? '生产记录'
              : this.pageName == 'steamInjectionInspectionRecord'
              ? '注汽检查记录'
              : this.pageName == 'solidWasteRecord'
              ? '固废记录'
              : this.pageName == 'qualityTestRecords'
              ? '质量检查检测记录'
              : this.pageName == 'QualityInspection'
              ? '来煤质检记录'
              : this.pageName == 'HaulSlag'
              ? '拉渣记录'
              : this.pageName == 'TransportAsh'
              ? '拉灰记录'
              : '锅炉运行记录'
          ),
          dispatchType
        );
      },
      async deleteRow(id) {
        await recordrulesplanDelete([id]);
        this.$message.success('删除成功');
        this.reload();
      },
      async revoke(id) {
        await recordrulesplanRevoke({ id });
        this.$message.success('撤回成功');
        this.reload();
      },
      handleRevoke(row) {
        if (row.dispatchType == 1) {
          // 多次派单，打开批量撤回弹窗
          this.$refs.batchRevokeDialogRef.open(row.code);
        } else {
          // 单次派单，直接撤回
          this.$confirm('确定要撤回此条数据吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.revoke(row.id);
          }).catch(() => {});
        }
      }
    }
  };
</script>

<style></style>
