<template>
  <div class="list-container">
    <vab-query-form>
      <vab-query-form-top-panel>
        <el-form ref="queryForm" :inline="true" :model="queryForm" @submit.native.prevent>
          <el-form-item prop="name">
            <el-input v-model="queryForm.name" placeholder="工单名称" @keyup.enter.native="fetchData" />
          </el-form-item>
          <el-form-item prop="orderTypeName">
            <el-input v-model="queryForm.orderTypeName" placeholder="工单类型" @keyup.enter.native="fetchData" />
          </el-form-item>
          <el-form-item prop="orderStatus">
            <el-select
              v-model="queryForm.orderStatus"
              clearable
              placeholder="工单状态"
              style="width: 100%"
              @keyup.enter.native="fetchData">
              <el-option v-for="item in orderStatusOptions" :key="item.key" :label="item.value" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item prop="productLine">
            <el-select
              v-model="queryForm.productLine"
              clearable
              placeholder="产品线"
              style="width: 100%"
              @change="changeProductLine">
              <el-option v-for="item in productLineOptions" :key="item.key" :label="item.value" :value="item.key" />
            </el-select>
          </el-form-item>
          <el-form-item prop="assignUserName">
            <el-input v-model="queryForm.assignUserName" placeholder="支持人员姓名" @keyup.enter.native="fetchData" />
          </el-form-item>
          <el-form-item prop="supportTime">
            <el-date-picker
              v-model="queryForm.supportTime"
              end-placeholder="日期结束"
              range-separator="至"
              start-placeholder="日期开始"
              type="daterange"
              value-format="yyyy-MM-dd" />
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="fetchData">查询</el-button>
            <el-button icon="el-icon-refresh-right" @click="reset">重置</el-button>
          </el-form-item>
        </el-form>
      </vab-query-form-top-panel>
      <vab-query-form-left-panel :span="12">
        <!--        <el-button icon="el-icon-plus" size="mini" type="primary" @click="handleEdit">新建</el-button>-->
      </vab-query-form-left-panel>
      <vab-query-form-right-panel :span="12">
        <table-tool :columns="columns" :show-columns.sync="showColumns" table-type="workOrderTable" />
      </vab-query-form-right-panel>
    </vab-query-form>

    <el-table ref="table" v-loading="listLoading" border :data="list" :height="$baseTableHeight(2)">
      <el-table-column align="center" label="序号" show-overflow-tooltip width="80">
        <template #default="{ $index }">
          {{ $index + 1 }}
        </template>
      </el-table-column>
      <el-table-column
        v-for="(item, index) in showColumns"
        :key="index"
        align="center"
        :label="item.label"
        :prop="item.prop"
        show-overflow-tooltip
        :sortable="item.sortable"
        :width="item.width">
        <template #default="{ row }">
          <el-button v-if="item.prop === 'id'" style="font-size: 14px" type="text" @click="handleDetail(row)">
            {{ row.id }}
          </el-button>
          <span v-else-if="item.prop === 'orderStatus'">
            {{ selectDictLabel(orderStatusOptions, row.orderStatus) }}
          </span>
          <span v-else-if="item.prop === 'productLine'">
            {{ row.productLineName ? row.productLineName : selectDictLabel(productLineOptions, row.productLine) }}
          </span>
          <span v-else-if="item.prop === 'createdTime'">
            {{ parseTime(row.createdTime, '{y}-{m}-{d}') }}
          </span>
          <span v-else-if="item.prop === 'endTime'">
            {{ overdue(row.endTime) }}
          </span>
          <el-button v-else-if="item.prop === 'nboName'" class="link-button" type="text" @click="handleProjDetail(row)">
            {{ row[item.prop] }}
          </el-button>
          <span v-else>{{ row[item.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ row }">
          <el-button v-if="row.orderStatus == 10 || row.orderStatus == 30" type="text" @click="handleClose(row.id)">
            关闭
          </el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-image class="vab-data-empty" :src="require('@/assets/empty_images/data_empty.png')" />
      </template>
    </el-table>

    <el-pagination
      background
      :current-page="queryForm.pageNum"
      :layout="layout"
      :page-size="queryForm.pageSize"
      :total="total"
      @current-change="handleCurrentChange"
      @size-change="handleSizeChange" />
    <!--创建工单-->
    <edit ref="edit" @fetch-data="fetchData" />
  </div>
</template>

<script>
  import to from 'await-to-js'
  import api from '@/api/work/index'
  import TableTool from '@/components/table/TableTool'
  import Edit from './components/Edit'

  export default {
    name: 'WorkOrder',
    components: { TableTool, Edit },
    data() {
      return {
        activeName: 'first',
        layout: 'total, sizes, prev, pager, next, jumper',
        queryForm: {
          name: '',
          orderTypeName: '',
          orderStatus: '',
          assignUserName: '',
          supportTime: [],
          productLine: '',
          pageNum: 1,
          pageSize: 10,
        },
        total: 0,
        listLoading: false,
        list: [],
        selectRows: [],
        showColumns: [],
        productLineOptions: [],
        columns: [
          {
            label: '工单编号',
            width: '80px',
            prop: 'id',
            disableCheck: true,
          },
          {
            label: '工单标题',
            width: '320px',
            prop: 'name',
            disableCheck: true,
          },
          {
            label: '工单类型',
            width: '200px',
            prop: 'orderTypeName',
          },
          {
            label: '工单状态',
            width: '100px',
            prop: 'orderStatus',
          },
          {
            label: '关联客户',
            width: '320px',
            prop: 'custName',
          },
          {
            label: '关联项目',
            width: '320px',
            prop: 'nboName',
          },
          {
            label: '产品线',
            width: '160px',
            prop: 'productLine',
          },
          {
            label: '负责人',
            width: '120px',
            prop: 'assignUserName',
          },
          {
            label: '是否超期',
            width: 'auto',
            prop: 'endTime',
          },
          {
            label: '申请人',
            width: '120px',
            prop: 'createdName',
          },
        ],
        orderStatusOptions: [],
      }
    },
    watch: {
      showColumns: function () {
        this.$nextTick(() => this.$refs.table.doLayout())
      },
    },
    activated() {
      this.fetchData()
    },
    mounted() {
      this.getOptions()
      this.fetchData()
    },

    methods: {
      changeProductLine() {},
      getOptions() {
        Promise.all([this.getDicts('work_order_status'), this.getDicts('sys_product_line')])
          .then(([workOrderStatus, productLine]) => {
            this.orderStatusOptions = workOrderStatus.data.values || []
            this.productLineOptions = productLine.data.values || []
          })
          .catch((err) => console.log(err))
      },
      overdue(endTime) {
        if (endTime) {
          var oDate1 = new Date()
          var oDate2 = new Date(endTime)
          if (oDate1.getTime() > oDate2.getTime()) {
            return '是' //第一个大
          } else {
            return '否' //第二个大
          }
        } else {
          return '否'
        }
      },
      async fetchData() {
        this.listLoading = true
        const params = { ...this.queryForm }
        const [err, res] = await to(api.getList(params))
        if (err) return (this.listLoading = false)
        if (res.data.list) {
          res.data.list.filter((i) => {
            let idata = JSON.parse(i.formData)
            idata.filter((field) => {
              if (field.name == '产品线') {
                i.productLineName = field.value
              }
            })
          })
        }
        this.list = res.data.list || []
        this.total = res.data.total
        this.listLoading = false
        this.$nextTick(() => this.$refs.table.doLayout())
      },
      handleEdit(row) {
        if (row.id) {
          this.$refs['edit'].showEdit(row)
        } else {
          this.$refs['edit'].showEdit()
        }
      },
      // 关闭工单
      handleClose(id) {
        this.$confirm('确认关闭?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(async () => {
            const [err, res] = await to(api.closeWorkOrder({ orderId: id }))
            if (err) return
            if (res.code == 200) {
              this.fetchData()
              this.$message({
                type: 'success',
                message: '关闭成功!',
              })
            }
          })
          .catch(() => {})
      },
      //详情
      handleDetail(row) {
        this.$router.push({
          name: 'WorkOrderDetail',
          query: {
            id: row.id,
          },
        })
      },
      handleProjDetail(row) {
        this.$router.push({
          path: '/opportunity/detail',
          query: {
            id: row.nboId,
          },
        })
      },
      reset() {
        this.queryForm = {
          pageNum: 1,
          pageSize: 10,
          name: '',
          orderTypeName: '',
          orderStatus: '',
          assignUserName: '',
          supportTime: [],
          productLine: '',
          nboName: '',
          custName: '',
        }
        this.fetchData()
      },

      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.fetchData()
      },
      setSelectRows(val) {
        this.selectRows = val
      },
    },
  }
</script>

<style lang="scss" scoped>
  $base: '.list';
</style>
