<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="progressTitle">
            <el-input v-model="queryForm.progressTitle" placeholder="任务标题" @keyup.enter.native="restFetchData" />
          </el-form-item>
          <el-form-item prop="progressType">
            <el-select
              v-model="queryForm.progressType"
              clearable
              placeholder="任务类型"
              style="width: 100%"
              @keyup.enter.native="restFetchData">
              <el-option label="发货任务单" value="10" />
              <el-option label="组装任务单" value="20" />
              <el-option label="部署安装单" value="30" />
            </el-select>
          </el-form-item>
          <el-form-item prop="progressStatus">
            <el-select
              v-model="queryForm.progressStatus"
              clearable
              placeholder="任务状态"
              style="width: 100%"
              @keyup.enter.native="restFetchData">
              <el-option label="未开始" value="10" />
              <el-option label="进行中" value="20" />
              <el-option label="已完成" value="30" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button icon="el-icon-search" type="primary" @click="restFetchData">查询</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" />
      <vab-query-form-right-panel :span="12">
        <table-tool :columns="columns" :show-columns.sync="showColumns" table-type="ProgressTable" />
      </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"
        :min-width="item.minWidth"
        :prop="item.prop"
        show-overflow-tooltip
        :sortable="item.sortable"
        :width="item.width">
        <template #default="{ row }">
          <el-button
            v-if="item.prop === 'progressTitle'"
            style="font-size: 14px"
            type="text"
            @click="handleWorkDetail(row)">
            {{ row.progressTitle }}
          </el-button>
          <span v-else-if="item.prop === 'progressLevel'">
            <el-select
              v-model="row.progressLevel"
              :disabled="row.progressStatus == 30"
              placeholder="请选择"
              @change="changeprogressLevel($event, row)">
              <el-option label="最高" value="10" />
              <el-option label="普通" value="20" />
              <el-option label="较低" value="30" />
            </el-select>
          </span>
          <span v-else-if="item.prop === 'progressStatus'">
            {{ progressStatusObj[row.progressStatus] }}
          </span>
          <span v-else-if="item.prop === 'startDate'">
            {{ parseTime(row.startDate, '{y}-{m}-{d}') }}
          </span>
          <span v-else-if="item.prop === 'endDate'">
            {{ parseTime(row.endDate, '{y}-{m}-{d}') }}
          </span>
          <span v-else-if="item.prop === 'reaStartDate'">
            {{ parseTime(row.reaStartDate, '{y}-{m}-{d}') }}
          </span>
          <span v-else-if="item.prop === 'reaEndDate'">
            {{ parseTime(row.reaEndDate, '{y}-{m}-{d}') }}
          </span>
          <span v-else-if="item.prop == 'progressType'">
            {{ getProgressType(row.progressType) }}
          </span>
          <span v-else>{{ row[item.prop] }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" fixed="right" label="操作" show-overflow-tooltip width="120">
        <template #default="{ row }">
          <el-button v-if="row.progressStatus != 30" type="text" @click="handleWorkEdit(row)">编辑</el-button>
          <el-button
            v-if="row.progressStatus == 10 && userId == row.principalPersonId"
            type="text"
            @click="handleStartWork(row)">
            开始
          </el-button>
          <el-button
            v-if="
              row.progressStatus == 20 &&
              row.deliverStatus == '20' &&
              row.progressType == '10' &&
              userId == row.principalPersonId
            "
            type="text"
            @click="handleDeliverGoods(row)">
            发货
          </el-button>
          <!-- <el-button
            v-if="row.progressStatus == 20 && row.deliverStatus == '30' && row.progressType == '10' && userId == saleId"
            type="text"
            @click="handleInspectGoods(row)">
            验收
          </el-button> -->
          <el-button
            v-if="
              row.progressStatus == 20 &&
              row.deliverStatus == '40' &&
              row.progressType == '10' &&
              userId == row.principalPersonId
            "
            type="text"
            @click="handleConfirmArrival(row)">
            确认到货
          </el-button>
          <el-button
            v-if="row.progressStatus == 20 && row.progressType == '' && userId == row.principalPersonId"
            type="text"
            @click="handleFinishWork(row)">
            完成
          </el-button>
          <el-button
            v-if="
              row.progressStatus == 20 &&
              row.deliverStatus == '60' &&
              row.progressType == '10' &&
              userId == row.principalPersonId
            "
            type="text"
            @click="handleFinishWork(row)">
            完成
          </el-button>
          <el-button
            v-if="row.progressStatus == 20 && row.progressType == '20' && userId == row.principalPersonId"
            type="text"
            @click="handleComplete(row)">
            完成
          </el-button>
          <el-button
            v-if="row.progressStatus == 20 && row.progressType == '30' && userId == row.principalPersonId"
            type="text"
            @click="handleComplete(row)">
            完成
          </el-button>
          <!-- <el-button v-show="row.progressStatus == 10" type="text" @click="handleDelete(row)">删除</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" />
    <!-- 完成 -->
    <completeProgress ref="complete" @fetch-data="fetchData" />
    <!-- 发货 -->
    <deliver ref="deliver" @fetch-data="fetchData" />
    <!-- 验收 -->
    <inspect ref="inspect" @fetch-data="fetchData" />
    <!-- 编辑 -->
    <edit-work ref="editWork" @fetch-data="fetchData" />
    <!-- 详情 -->
    <detailWork ref="detailWork" />
  </div>
</template>

<script>
  import to from 'await-to-js'
  import TableTool from '@/components/table/TableTool'
  import deliverWorkApi from '@/api/work/deliverWork'
  import { mapGetters } from 'vuex'
  import completeProgress from '@/views/work/deliver/components/completeProgress'
  import deliver from '@/views/work/deliver/components/deliver'
  import inspect from '@/views/work/deliver/components/inspect'
  import EditWork from '@/views/work/deliver/components/editWork'
  import detailWork from '@/views/work/deliver/components/detailWork'

  export default {
    name: 'Progress',
    components: { TableTool, completeProgress, deliver, inspect, EditWork, detailWork },
    data() {
      return {
        progressStatusObj: {
          10: '未开始',
          20: '进行中',
          30: '已完成',
        },
        layout: 'total, sizes, prev, pager, next, jumper',
        queryForm: {
          progressTitle: '',
          progressType: '',
          progressStatus: '',
          pageNum: 1,
          pageSize: 10,
          isPrincipalPerson: '1',
        },
        total: 0,
        listLoading: false,
        list: [],
        showColumns: [],
        columns: [
          {
            label: '任务标题',
            width: '160px',
            prop: 'progressTitle',
            sortable: false,
            disableCheck: true,
          },
          {
            label: '任务类型',
            width: '120px',
            prop: 'progressType',
            sortable: false,
          },
          // {
          //   label: '任务内容',
          //   prop: 'progressContext',
          //   minWidth: 'auto',
          //   sortable: false,
          //   disableCheck: true,
          // },
          {
            label: '优先级',
            width: '120px',
            prop: 'progressLevel',
            sortable: false,
          },
          {
            label: '负责人',
            width: '120px',
            prop: 'principalPerson',
            sortable: false,
          },
          {
            label: '状态',
            width: '120px',
            prop: 'progressStatus',
            sortable: false,
          },
          {
            label: '计划开始时间',
            width: '160px',
            prop: 'startDate',
            sortable: false,
          },

          {
            label: '计划结束时间',
            width: '160px',
            prop: 'endDate',
            sortable: false,
          },
          {
            label: '实际开始时间',
            width: '160px',
            prop: 'reaStartDate',
            sortable: false,
          },

          {
            label: '实际结束时间',
            width: '160px',
            prop: 'reaEndDate',
            sortable: false,
          },
          {
            label: '备注',
            width: 'auto',
            prop: 'remark',
            sortable: false,
          },
        ],
      }
    },
    computed: {
      ...mapGetters({
        userId: 'user/id',
      }),
    },
    watch: {
      showColumns: function () {
        this.$nextTick(() => this.$refs.table.doLayout())
      },
    },
    activated() {
      this.fetchData()
    },
    mounted() {
      this.fetchData()
    },

    methods: {
      restFetchData() {
        this.queryForm.pageNum = 1
        this.fetchData()
      },
      async fetchData() {
        this.listLoading = true
        const params = { ...this.queryForm }
        params.isPage = '1'
        const [err, res] = await to(deliverWorkApi.list({ ...params }))
        this.listLoading = false
        if (err) return (this.listLoading = false)
        if (res.code == 200 && res.data) {
          this.list = res.data.list || []
          this.total = res.data.total
        }
        this.$nextTick(() => this.$refs.table.doLayout())
      },
      reset() {
        this.queryForm = {
          progressTitle: '',
          progressType: '',
          progressStatus: '',
          pageNum: 1,
          pageSize: 10,
          isPrincipalPerson: '1',
        }
        this.fetchData()
      },
      handleSizeChange(val) {
        this.queryForm.pageSize = val
        this.fetchData()
      },
      handleCurrentChange(val) {
        this.queryForm.pageNum = val
        this.fetchData()
      },
      //工作项详情
      handleWorkEdit(row) {
        this.$refs['editWork'].open(row.planId, row.deliverOrderId, '', row.progressStatus != 30, row)
      },
      //工作项详情
      handleWorkDetail(row) {
        this.$refs['detailWork'].open(row.planId, row.deliverOrderId, row)
      },
      // 获取任务类型
      getProgressType(type) {
        if (type == '') {
          return '软件任务单'
        } else if (type == '10') {
          return '发货任务单'
        } else if (type == '20') {
          return '组装任务单'
        } else if (type == '30') {
          return '部署安装单'
        }
        return '未知类型'
      },
      // 开始工作项
      async handleStartWork(row) {
        this.$prompt('你确定要开始当前任务吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        })
          .then(async ({ value }) => {
            // 当用户点击确定按钮时，执行的逻辑
            const [err, res] = await to(deliverWorkApi.startWork({ id: row.id, remark: value }))
            if (err) return
            if (res.code == 200) {
              this.$baseMessage(res.msg, 'success', 'vab-hey-message-success')
              this.fetchData()
            }
          })
          .catch(() => {
            // 当用户点击取消按钮时，执行的逻辑
            console.log('取消输入')
          })
      },
      // 打开组装完成弹窗
      handleComplete(row) {
        this.$refs.complete.open(row)
      },
      // 发货
      handleDeliverGoods(row) {
        this.$refs.deliver.open(row)
      },
      // 验收
      handleInspectGoods(row) {
        this.$refs.inspect.open(row)
      },
      // 确认到货
      async handleConfirmArrival(row) {
        this.$prompt('你确定货物已到达吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        })
          .then(async ({ value }) => {
            // 当用户点击确定按钮时，执行的逻辑
            const [err, res] = await to(deliverWorkApi.confirmArrival({ id: row.id, remark: value }))
            if (err) return
            if (res.code == 200) {
              this.$baseMessage(res.msg, 'success', 'vab-hey-message-success')
              this.fetchData()
            }
          })
          .catch(() => {
            // 当用户点击取消按钮时，执行的逻辑
            console.log('取消输入')
          })
      },
      // 完成工作项
      async handleFinishWork(row) {
        this.$prompt('你确定要完成当前任务吗', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
        })
          .then(async ({ value }) => {
            // 当用户点击确定按钮时，执行的逻辑
            console.log('输入的值为:', value)
            const [err, res] = await to(deliverWorkApi.finishWork({ id: row.id, remark: value }))
            if (err) return
            if (res.code == 200) {
              this.$baseMessage(res.msg, 'success', 'vab-hey-message-success')
              this.fetchData()
            }
          })
          .catch(() => {
            // 当用户点击取消按钮时，执行的逻辑
            console.log('取消输入')
          })
      },
      handleDelete(row) {
        this.$baseConfirm('你确定要删除当前项吗', null, async () => {
          const { msg } = await deliverWorkApi.delete({ id: [row.id] })
          this.$baseMessage(msg, 'success', 'vab-hey-message-success')
          await this.fetchData()
        })
      },
      async changeprogressLevel(val, row) {
        const params = {
          id: row.id,
          progressLevel: val,
        }
        const [err, res] = await to(deliverWorkApi.update(params))
        if (err) return
        if (res.code == 200) {
          this.$baseMessage(res.msg, 'success', 'vab-hey-message-success')
        }
        this.fetchData()
      },
    },
  }
</script>

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