<template>
  <a-card :bordered="false">
    <!-- 查询区域 -->
    <div class="table-page-search-wrapper">
      <a-form layout="inline" @keyup.enter.native="searchQuery">
        <a-row :gutter="24">
          <a-col :xl="4" :lg="5" :md="7" :sm="24">
            <a-form-item label="工单类型">
              <j-dict-select-tag
                v-model="queryParam.modelType"
                dictCode="work_order"
                placeholder="请选择工单类型"
              />
            </a-form-item>
          </a-col>
          <a-col :xl="4" :lg="5" :md="7" :sm="24">
            <a-form-item label="设备">
              <a-input placeholder="请输入设备" v-model="queryParam.deviceId"></a-input>
            </a-form-item>
          </a-col>
          <template v-if="toggleSearchStatus">
            <a-col :xl="4" :lg="5" :md="7" :sm="24">
              <a-form-item label="工单状态">
                <j-dict-select-tag
                  v-model="queryParam.status"
                  dictCode="work_order_status"
                  placeholder="请选择工单类型"
                />
              </a-form-item>
            </a-col>
            <a-col :xl="4" :lg="5" :md="7" :sm="24">
              <a-form-item label="工单配合人">
                <j-dict-select-tag v-model="queryParam.executor" dictCode="sys_user,realname,id" placeholder="请选择工单配合人"/>
              </a-form-item>
            </a-col>
            <a-col :xl="4" :lg="5" :md="7" :sm="24">
              <a-form-item label="工单负责人">
                <j-dict-select-tag v-model="queryParam.coordinator" dictCode="sys_user,realname,id" placeholder="请选择负责人"/>
              </a-form-item>
            </a-col>
            <a-col :xl="8" :lg="10" :md="12" :sm="24">
              <a-form-item label="开工时间">
                <j-date :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择开始时间" class="query-group-cust" v-model="queryParam.startTime_begin"></j-date>
                <span class="query-group-split-cust"></span>
                <j-date :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择结束时间" class="query-group-cust" v-model="queryParam.startTime_end"></j-date>
              </a-form-item>
            </a-col>
            <a-col :xl="8" :lg="10" :md="12" :sm="24">
              <a-form-item label="完工时间">
                <j-date :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择开始时间" class="query-group-cust" v-model="queryParam.finishTime_begin"></j-date>
                <span class="query-group-split-cust"></span>
                <j-date :show-time="true" date-format="YYYY-MM-DD HH:mm:ss" placeholder="请选择结束时间" class="query-group-cust" v-model="queryParam.finishTime_end"></j-date>
              </a-form-item>
            </a-col>
          </template>
          <a-col :xl="6" :lg="7" :md="8" :sm="24">
            <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" icon="search">查询</a-button>
              <a-button type="primary" @click="searchReset" icon="reload" style="margin-left: 8px">重置</a-button>
              <a @click="handleToggleSearch" style="margin-left: 8px">
                {{ toggleSearchStatus ? '收起' : '展开' }}
                <a-icon :type="toggleSearchStatus ? 'up' : 'down'"/>
              </a>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>
    <!-- 查询区域-END -->

    <!-- 操作按钮区域 -->
    <div class="table-operator">
      <a-button @click="handleAdd" type="primary" icon="plus">新增</a-button>
      <a-button type="primary" icon="download" @click="handleExportXls('任务工单')">导出</a-button>
      <a-upload name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader" :action="importExcelUrl" @change="handleImportExcel">
        <a-button type="primary" icon="import">导入</a-button>
      </a-upload>
      <!-- 高级查询区域 -->
      <j-super-query :fieldList="superFieldList" ref="superQueryModal" @handleSuperQuery="handleSuperQuery"></j-super-query>
      <a-dropdown v-if="selectedRowKeys.length > 0">
        <a-menu slot="overlay">
          <a-menu-item key="1" @click="batchDel"><a-icon type="delete"/>删除</a-menu-item>
        </a-menu>
        <a-button style="margin-left: 8px"> 批量操作 <a-icon type="down" /></a-button>
      </a-dropdown>
    </div>

    <!-- table区域-begin -->
    <div>
      <div class="ant-alert ant-alert-info" style="margin-bottom: 16px;">
        <i class="anticon anticon-info-circle ant-alert-icon"></i> 已选择 <a style="font-weight: 600">{{ selectedRowKeys.length }}</a>项
        <a style="margin-left: 24px" @click="onClearSelected">清空</a>
      </div>

      <a-table
        ref="table"
        size="middle"
        :scroll="{x:true}"
        bordered
        rowKey="id"
        :columns="columns"
        :dataSource="dataSource"
        :pagination="ipagination"
        :loading="loading"
        :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}"
        class="j-table-force-nowrap"
        @change="handleTableChange">

        <template slot="dictSlot" slot-scope="text,record">
          <a-popover placement="top">
            <template slot="content">
              <div >
                {{ record.planId_dictText }}
              </div>
            </template>
            <j-dict-tag v-if="text" dict-code="repair_range" :text="text"/>
            <p v-else></p>
          </a-popover>
        </template>
        <template slot="duration" slot-scope="text">
          <div>{{ formatDuration(text) }}</div>
        </template>
        <template slot="imgSlot" slot-scope="text,record">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无图片</span>
          <img v-else :src="getImgView(text)" :preview="record.id" height="25px" alt="" style="max-width:80px;font-size: 12px;font-style: italic;"/>
        </template>
        <template slot="fileSlot" slot-scope="text">
          <span v-if="!text" style="font-size: 12px;font-style: italic;">无文件</span>
          <a-button
            v-else
            :ghost="true"
            type="primary"
            icon="download"
            size="small"
            @click="downloadFile(text)">
            下载
          </a-button>
        </template>

        <span slot="action" slot-scope="text, record">
          <a v-if="record.status < 2" @click="handleEdit(record)">编辑</a>

          <a-divider v-if="record.status < 2" type="vertical" />
          <a-dropdown>
            <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
            <a-menu slot="overlay">
              <a-menu-item>
                <a @click="handleDetailModel(record)">详情</a>
              </a-menu-item>
              <a-menu-item v-if="record.status < 2">
                <a @click="handleDesignate(record)">派工</a>
              </a-menu-item>
               <a-menu-item v-if="record.status === 2 & record.materialStatus === 0">
                <a @click="handleApplyMaterials(record)">物料申请</a>
              </a-menu-item>
               <a-menu-item v-if="record.status === 2 & record.toolsStatus === 0">
                <a @click="handleApplyTools(record)">工器具申请</a>
              </a-menu-item>
               <a-menu-item v-if="record.status === 2 & record.pointRequestStatus === 0">
                <a @click="handleRequestPoint(record)">作业请点</a>
              </a-menu-item>
               <a-menu-item v-if="record.status === 3 & record.pointRequestStatus === 1">
                <a @click="handleDimissPoint(record)">作业销点</a>
              </a-menu-item>
              <a-menu-item v-if="record.status === 4">
                <a @click="openResource(record)">物资使用</a>
              </a-menu-item>
              <a-menu-item v-if="record.status === 5 || (record.status > 0 && record.status < 3)">
                <a-popconfirm title="确定撤销吗?" @confirm="() => handleCancelWork(record)">
                  <a>撤销</a>
                </a-popconfirm>
              </a-menu-item>
              <a-menu-item v-if="record.status === 5">
                <a @click="handleStartWork(record)">开工</a>
              </a-menu-item>
              <a-menu-item v-if="record.status === 3">
               <a @click="handleStopWork(record)">停工</a>
             </a-menu-item>
              <a-menu-item v-if="record.status === 3">
                <a @click="handleFinishWork(record)">完工</a>
              </a-menu-item>
             <a-menu-item v-if="record.status === 3">
               <a @click="handleStartOperate(record)">开始作业</a>
             </a-menu-item>
              <a-menu-item v-if="record.status === 0">
                <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
                  <a>删除</a>
                </a-popconfirm>
              </a-menu-item>
            </a-menu>
          </a-dropdown>
        </span>

      </a-table>
    </div>
    <ApplyDialog v-if="showApplyDialog" :title="dialogTitle"  :order-id="selectOrderId" v-model="showApplyDialog" @input="loadData"/>
    <work-order-modal ref="modalForm" @ok="modalFormOk"></work-order-modal>
    <work-order-detail-model :order-id="workOrder" :visible="detailModelVisible" @close="closeDetailModel" :masterFlag="true"></work-order-detail-model>
    <work-order-manage-form :visitor="visitor" :title="manageTitle" :work-order="workOrder" @close="manageClose"></work-order-manage-form>
    <work-permit-complete-modal ref="percomForm" @ok="modalFormOk"></work-permit-complete-modal>
    <work-modal ref="workModal"/>
    <work-division-set-modal ref="setModalForm" @ok="modalFormOk"></work-division-set-modal>
    <work-order-resource-modal
      :visible.sync="resourceVisible"
      :work-order-id="selectOrderId"
    />
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import { mixinDevice } from '@/utils/mixin'
  import { JeecgListMixin } from '@/mixins/JeecgListMixin'
  import WorkOrderModal from './modules/WorkOrderModal'
  import WorkOrderManageForm from '@views/workOrder/modules/WorkOrderManageForm.vue'
  import ApplyDialog from './components/ApplyDialog/index.vue'
  import WorkOrderDetailModel from '@views/workOrder/components/WorkOrderDetailModel/index.vue'
  import WorkPermitCompleteForm from '@views/workOrder/modules/WorkPermitCompleteForm.vue'
  import WorkPermitCompleteModal from '@views/workOrder/modules/WorkPermitCompleteModal.vue'
  import WorkModal from '@views/workOrder/modules/work/WorkModal.Style#Drawer.vue'
  import { getAction, postAction } from '@api/manage'
  import WorkDivisionSetModal from '@views/workOrder/modules/WorkDivisionSetModal.vue'
  import WorkOrderResourceModal from './components/WorkOrderResourceModal/WorkOrderResourceModal.vue'

  export default {
    name: 'WorkOrderList',
    mixins:[JeecgListMixin, mixinDevice],
    components: {
      WorkDivisionSetModal,
      WorkModal,
      WorkPermitCompleteModal,
      WorkPermitCompleteForm,
      WorkOrderDetailModel,
      WorkOrderManageForm,
      WorkOrderModal,
      ApplyDialog,
      WorkOrderResourceModal
    },
    data () {
      return {
        dialogTitle: "",
        selectOrderId: "",
        showApplyDialog: false,
        description: '任务工单管理页面',
        // 表头
        columns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'设备',
            align:"center",
            dataIndex: 'deviceId_dictText'
          },
          {
            title:'工单类型',
            align:"center",
            dataIndex: 'modelType_dictText'
          },
          // {
          //   title:'检修计划/维修计划',
          //   align:"center",
          //   dataIndex: 'planId'
          // },
          {
            title:'修程/故障类型',
            align:"center",
            dataIndex: 'regularId_dictText',
            scopedSlots: { customRender: 'dictSlot' }
          },
          // {
          //   title:'工单模板',
          //   align:"center",
          //   dataIndex: 'modelId'
          // },
          {
            title:'工单状态',
            align:"center",
            dataIndex: 'status_dictText'
          },
          // {
          //   title:'班组',
          //   align:"center",
          //   dataIndex: 'createDept_dictText'
          // },
          {
            title:'负责人',
            align:"center",
            dataIndex: 'coordinator_dictText'
          },
          // {
          //   title:'配合人',
          //   align:"center",
          //   dataIndex: 'executor_dictText'
          // },
          {
            title:'开工时间',
            align:"center",
            dataIndex: 'startTime'
          },
          {
            title:'完工时间',
            align:"center",
            dataIndex: 'finishTime'
          },
          {
            title:'作业时长',
            align:"center",
            dataIndex: 'workDuration',
            scopedSlots: { customRender: 'duration' }
          },
          {
            title:'备注',
            align:"center",
            dataIndex: 'remark'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          list: "/workOrder/workOrder/list",
          delete: "/workOrder/workOrder/delete",
          deleteBatch: "/workOrder/workOrder/deleteBatch",
          exportXlsUrl: "/workOrder/workOrder/exportXls",
          importExcelUrl: "workOrder/workOrder/importExcel",
          dsadd: "/workOrder/workDivision/add",

        },
        dictOptions:{},
        superFieldList:[],
        visitor: 0,
        manageTitle: '',
        workOrder: null,
        detailModelVisible: false,
        pcModalVisible: false,
        resourceVisible: false,
      }
    },
    created() {
    this.getSuperFieldList();
    },
    computed: {
      importExcelUrl: function(){
        return `${window._CONFIG['domianURL']}/${this.url.importExcelUrl}`;
      },
    },
    methods: {
      handleStartOperate(record){
        this.workOrder = record.id;
        this.$refs.workModal.show(this.workOrder)
      },
      handleApplyMaterials(record){
        this.selectOrderId = record.id;
        this.dialogTitle = "物料申请";
        this.showApplyDialog = true;
      },
      handleApplyTools(record){
        this.selectOrderId = record.id;
        this.dialogTitle = "工器具申请";
        this.showApplyDialog = true;
      },
      handleRequestPoint(record){
        this.pcModalVisible = true;
        this.$refs.percomForm.add(record);
        this.$refs.percomForm.title="请点";
      },
      async handleDimissPoint(record) {
        this.pcModalVisible = true;
        const res = await getAction('/workOrder/workPermitComplete/queryByWorkOrder', { workOrder: record.id });
        if (res.success && res.result != null) {
          const item = res.result;
          item.comple = 1;
          item.compleUser = record.coordinator;
          this.$refs.percomForm.edit(item);
          this.$refs.percomForm.title = "销点";
        }else
          this.$message.error(res.message)
      },
      initDictConfig(){
      },
      getSuperFieldList(){
        let fieldList=[];
        fieldList.push({type:'int',value:'modelType',text:'工单类型',dictCode:''})
        fieldList.push({type:'string',value:'modelId',text:'工单模板',dictCode:''})
        fieldList.push({type:'string',value:'planId',text:'检修计划/维修计划',dictCode:''})
        fieldList.push({type:'string',value:'deviceId',text:'设备',dictCode:''})
        fieldList.push({type:'string',value:'regularId',text:'修程/故障类型',dictCode:''})
        fieldList.push({type:'int',value:'status',text:'工单状态',dictCode:''})
        fieldList.push({type:'string',value:'executor',text:'工单配合人',dictCode:''})
        fieldList.push({type:'string',value:'coordinator',text:'工单负责人',dictCode:''})
        fieldList.push({type:'datetime',value:'startTime',text:'开工时间'})
        fieldList.push({type:'datetime',value:'finishTime',text:'完工时间'})
        fieldList.push({type:'string',value:'remark',text:'备注',dictCode:''})
        fieldList.push({type:'int',value:'deleteFlag',text:'是否删除0否1是',dictCode:''})
        this.superFieldList = fieldList
      },
      handleDesignate(record){
        // this.visitor = 1;
        // this.manageTitle = '派工';
        // this.workOrder = record.id;
        if(record.status!==0&&record.status!==1) {
          this.$message.error("工单已派工，不可重复派工！");
          return
        }
        let param = {};
        param.deviceId = record.deviceId;
        param.regularId = record.regularId;
        param.planId = record.planId;
        param.workOrder = record.id;
        postAction(this.url.dsadd,param).then(res=>{
          if (!res.success) {
            // 如果没有自动完成人员派工，打开派工页面
            this.$refs.setModalForm.add(param);
            this.$refs.setModalForm.disableSubmit = false;
          }else {
            this.$message.success("自动派工成功")
            this.loadData();
          }
        });
      },
      handleCancelWork(record) {
        this.visitor = 4;
        this.manageTitle = '撤销';
        this.workOrder = record.id;
      },
      handleStartWork(record){
        this.visitor = 2;
        this.manageTitle = '开工';
        this.workOrder = record.id;
      },
      handleStopWork(record){
        this.visitor = 7;
        this.manageTitle = '停工';
        this.workOrder = record.id;
      },
      handleFinishWork(record){
        this.visitor = 3;
        this.manageTitle = '完工';
        this.workOrder = record.id;
      },
      manageClose() {
        this.visitor = 0;
        this.manageTitle = '';
        this.workOrder = null;
        this.loadData();
      },
      handleDetailModel(record) {
        this.workOrder = record.id;
        this.detailModelVisible = true;
      },
      closeDetailModel() {
        this.detailModelVisible = false;
        this.workOrder = null;
      },
      openResource(record) {
        this.selectOrderId = record.id
        this.resourceVisible = true
      },
      formatDuration(ms) {
        if (!ms && ms !== 0) return '';

        const totalMinutes = Math.floor(ms / 1000 / 60);
        const days = Math.floor(totalMinutes / 1440);
        const hours = Math.floor((totalMinutes % 1440) / 60);
        const minutes = totalMinutes % 60;

        const parts = [];
        if (days) parts.push(days + '天');
        if (hours) parts.push(hours + '小时');
        if (minutes || parts.length === 0) parts.push(minutes + '分钟');

        return parts.join(' ');
      }
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less';
</style>
