<template>
  <a-card :bordered="false">
    <!-- 操作按钮区域 -->
    <div class="table-operator" v-if="selectedRowKeys.length!==0" >
      <a-button @click="handleDivision" type="primary">自动派工</a-button>
      <a-button @click="cancelDivision" type="primary">取消派工</a-button>
      <a-button @click="handleAdd" type="primary">完工</a-button>
      <a-button @click="handleAdd" type="primary">取消完工</a-button>
      <a-button @click="handleEditDivision" type="primary">人工调整</a-button>
      <a-button @click="handleAdd" type="primary">故障提报</a-button>
    </div>

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

        <a-table
          slot="expandedRowRender"
          slot-scope="text"
          v-loading="dloading"
          :columns="dcolumns"
          :data-source="details"
          :pagination="false"
          size="small"
        >
          <span slot="action" slot-scope="text, record">
            <a-popconfirm title="确定删除吗?" @confirm="() => handleDelete(record.id)">
              <a>删除</a>
            </a-popconfirm>
          </span>
        </a-table>
        <template slot="statusSlot" slot-scope="text">
          <a-tag v-if="text===0">未派工</a-tag>
          <j-dict-tag v-else dict-code="work_order_status" :text="text.toString()"/>
        </template>

      </a-table>
    </div>

    <work-division-modal ref="modalForm" @ok="modalFormOk"></work-division-modal>
    <work-division-set-modal ref="setModalForm" @ok="modalFormOk"></work-division-set-modal>
  </a-card>
</template>

<script>

  import '@/assets/less/TableExpand.less'
  import WorkDivisionModal from '@views/workOrder/modules/WorkDivisionModal.vue'
  import dayjs from 'dayjs'
  import { deleteAction, getAction, postAction } from '@api/manage'
  import WorkDivisionSetModal from '@views/workOrder/modules/WorkDivisionSetModal.vue'

  export default {
    name: 'DivisionList',
    components: {
      WorkDivisionSetModal,
      WorkDivisionModal
    },
    props: {
      tabNum: {//0,1,2,3
        type: Number,
        default: 3,
        required: true
      },
    },
    watch: {
      tabNum(newVal, oldVal) {
        if(newVal) this.getWorderDiviList()
      }
    },
    data () {
      return {
        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',
            scopedSlots: { customRender: 'statusSlot' }
          },
          // {
          //   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: 'remark'
          },
          // {
          //   title: '操作',
          //   dataIndex: 'action',
          //   align:"center",
          //   fixed:"right",
          //   width:147,
          //   scopedSlots: { customRender: 'action' }
          // }
        ],
        dictOptions:{},
        superFieldList:[],
        ipagination:{
          current: 1,
          pageSize: 10,
          pageSizeOptions: ['10', '20', '30'],
          showTotal: (total, range) => {
            return range[0] + "-" + range[1] + " 共" + total + "条"
          },
          showQuickJumper: true,
          showSizeChanger: true,
          total: 0
        },
        worderDiviList:[],
        loading: false,
        selectedRowKeys: [],
        queryParam: {},
        dloading: false,
        details: [],
        dcolumns: [
          {
            title: '#',
            dataIndex: '',
            key:'rowIndex',
            width:60,
            align:"center",
            customRender:function (t,r,index) {
              return parseInt(index)+1;
            }
          },
          {
            title:'人员编号',
            align:"center",
            dataIndex: 'executor'
          },
          {
            title:'人员姓名',
            align:"center",
            dataIndex: 'executorName'
          },
          {
            title:'联系电话',
            align:"center",
            dataIndex: 'execPhone'
          },
          {
            title:'人员类型',
            align:"center",
            dataIndex: 'torType_dictText'
          },
          {
            title:'备注',
            align:"center",
            dataIndex: 'remark'
          },
          {
            title: '操作',
            dataIndex: 'action',
            align:"center",
            fixed:"right",
            width:147,
            scopedSlots: { customRender: 'action' }
          }
        ],
        url: {
          dsadd: "/workOrder/workDivision/add",
          dscancel: "/workOrder/workDivision/cancel",
          dslist: "/workOrder/workDivision/allist",
          wlist: "/workOrder/workOrder/list",
          ddelete: "/workOrder/workDivisionSet/delete",
          delete: "/workOrder/workDivision/delete",
        },
      }
    },
    mounted() {
      this.getWorderDiviList();
    },
    methods: {
      initDictConfig(){
      },
      handleAdd() {},
      handleDivision(){
        if(this.selectionRows[0].status!==0&&this.selectionRows[0].status!==1) {
          this.$message.error("工单已派工，不可重复派工！");
          return
        }
        let param = {};
        param.deviceId = this.selectionRows[0].deviceId;
        param.regularId = this.selectionRows[0].regularId;
        param.planId = this.selectionRows[0].planId;
        param.workOrder = this.selectionRows[0].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.getWorderDiviList();
          }
        });
      },
      cancelDivision(){
        deleteAction(this.url.dscancel, {workOrder:this.selectionRows[0].id}).then(res=>{
          if (res.success) {
            this.$message.success("取消成功")
            this.getWorderDiviList();
          }else {
            this.$message.error("取消失败")
          }
        });
      },
      handleEditDivision(){
        if(this.selectionRows[0].status==3 || this.selectionRows[0].status==4) {
          this.$message.error("工单已开工，不可调整！");
          return
        }
        this.$refs.modalForm.add(this.selectionRows[0]);
        this.$refs.modalForm.disableSubmit = false;
      },
      handleExpand(expand,record){
        if(expand){
          //加载详细信息
          this.dloading = true;
          getAction(this.url.dslist, {
            workOrder:record.id,
          }).then((res) => {
            this.details = res.result
            this.dloading = false;
          })
        }
      },
      onSelectChange(selectedRowKeys, selectionRows) {
        this.selectedRowKeys = selectedRowKeys;
        this.selectionRows = selectionRows;
      },
      onClearSelected() {
        this.selectedRowKeys = [];
        this.selectionRows = [];
      },
      handleTableChange(pagination, filters, sorter) {
        //分页变化时触发
        this.ipagination = pagination;
        this.getWorderDiviList();
      },
      modalFormOk() {
        // 新增/修改 成功时，重载列表
        this.getWorderDiviList();
        //清空列表选中
        this.onClearSelected()
      },
      getWorderDiviList(){
        if(this.tabNum !== 3) {
          const timeDay = dayjs().add(this.tabNum,'day');
          this.queryParam.createTime_begin = timeDay.startOf('day').format('YYYY-MM-DD HH:mm:ss');
          this.queryParam.createTime_end = timeDay.endOf('day').format('YYYY-MM-DD HH:mm:ss');
        }
        this.queryParam.pageNo = this.ipagination.current;
        this.queryParam.pageSize = this.ipagination.pageSize;
        this.loading = true;
        getAction(this.url.wlist, this.queryParam).then(res => {
          if (res.success) {
            this.worderDiviList = res.result.records
            if(res.result.total)
            {
              this.ipagination.total = res.result.total;
            }else{
              this.ipagination.total = 0;
            }
          }
          else
            this.$message.warning(res.message || '获取待派工单失败')
        }).finally(() => {
          this.loading = false
        });
      },
      handleDelete: function (id) {
        if(!this.url.ddelete){
          this.$message.error("请设置url.ddelete属性!")
          return
        }
        var that = this;
        deleteAction(that.url.delete, {id: id}).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            that.getWorderDiviList();
          } else {
            that.$message.warning(res.message);
          }
        });
      },
    }
  }
</script>

<style scoped>

</style>