<!-- 我的工作台 -->
<template>
  <div class="works">
    <el-form :model="dataForm" :inline="true">
      <el-form-item label="选择用户">
        <user-component
          v-model="dataForm.userId"
          :user-id="dataForm.userId"
          @userSelected="userChanged"
        />
      </el-form-item>
      <el-form-item>
        <el-button @click="queryData()">查询</el-button>
      </el-form-item>
    </el-form>
    <el-radio-group @change="queryData" v-model="dataForm.state">
      <el-radio-button
        v-for="item in optionsState"
        :key="item.code"
        :label="item.code"
        >{{ item.value }}</el-radio-button
      >
    </el-radio-group>
    <el-table
      :data="dataList"
      border
      v-loading="dataListLoading"
      style="width: 100%; margin-top: 20px"
    >
      <el-table-column label="序号" type="index" width="50" align="center">
      </el-table-column>
      <el-table-column
        prop="taskName"
        header-align="center"
        align="center"
        min-width="140"
        :show-tooltip-when-overflow="true"
        label="任务名称"
      >
      </el-table-column>
      <el-table-column
        v-if="Number(dataForm.state) !== 2"
        prop="completeNum"
        header-align="center"
        align="center"
        min-width="160"
        label="任务进度"
      >
        <template slot-scope="scope">
          <el-progress
            :percentage="
              getPercentage(scope.row.completeNum, scope.row.totalNum)
            "
          ></el-progress>
        </template>
      </el-table-column>
      <el-table-column
        prop="planCompletionTime"
        header-align="center"
        align="center"
        min-width="160"
        label="规定完成时间"
      >
      </el-table-column>
      <el-table-column
        prop="historicalOperationRecords"
        header-align="center"
        align="center"
        width="160"
        :show-tooltip-when-overflow="true"
        label="操作历史记录"
      >
      </el-table-column>
      <el-table-column
        prop="nodeName"
        header-align="center"
        align="center"
        min-width="160"
        :show-tooltip-when-overflow="true"
        label="工序内容"
      >
      </el-table-column>
      <el-table-column
        prop="require"
        header-align="center"
        align="center"
        width="160"
        :show-tooltip-when-overflow="true"
        label="工序要求"
      >
      </el-table-column>
      <el-table-column
        prop="explain"
        header-align="center"
        align="center"
        width="160"
        :show-tooltip-when-overflow="true"
        label="工序说明"
      >
      </el-table-column>
      <el-table-column
        header-align="center"
        align="center"
        min-width="200"
        label="工序附件"
      >
        <template slot-scope="scope">
          <div
            v-for="(item, index) in scope.row.attachList"
            style="display: inline"
          >
            <span v-if="index > 0">,</span>
            <a
              :key="item.fileName + index"
              type="primary"
              href="#"
              @click="previewFile(item.fileName, item.url)"
              >{{ item.fileName }}</a
            >
          </div>
        </template>
      </el-table-column>
      <el-table-column
        v-if="Number(dataForm.state) === 3"
        prop="operationRecords"
        header-align="center"
        align="center"
        min-width="160"
        :show-tooltip-when-overflow="true"
        label="完成记录说明"
      >
      </el-table-column>
      <el-table-column
        v-if="opColVisible"
        fixed="right"
        header-align="center"
        align="center"
        width="180"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            v-if="isAuth('work:clt:start') && Number(scope.row.state) < 2"
            :disabled="Number(scope.row.state) === 0"
            type="text"
            size="small"
            @click="startTask(scope.row.taskId)"
            >开始</el-button
          >
          <!--          <el-button v-if="isAuth('work:clt:start')" type="text" size="small" @click="startTask(scope.row.taskId)">开始</el-button>-->
          <el-button
            v-if="isAuth('work:clt:transfer') && Number(scope.row.state) !== 3"
            type="text"
            size="small"
            @click="transferTask(scope.row.taskId, scope.row.workTypeId)"
            >转单</el-button
          >
          <el-button
            v-if="
              isAuth('work:clt:complete') &&
              Number(scope.row.state) === 2 &&
              (scope.row.nodeType == null ||
                scope.row.nodeType === 'start' ||
                scope.row.nodeType === 'produce')
            "
            type="text"
            size="small"
            @click="completeTask(scope.row.taskId)"
            >完成</el-button
          >
          <el-button
            v-if="
              isAuth('work:clt:check') &&
              Number(scope.row.state) === 2 &&
              (scope.row.nodeType === 'check' ||
                scope.row.nodeType === 't-check')
            "
            type="text"
            size="small"
            @click="checkTask(scope.row.taskId, 1)"
            >通过</el-button
          >
          <el-button
            v-if="
              isAuth('work:clt:check') &&
              Number(scope.row.state) === 2 &&
              (scope.row.nodeType === 'check' ||
                scope.row.nodeType === 't-check')
            "
            type="text"
            size="small"
            @click="checkTask(scope.row.taskId, 2)"
            >不通过</el-button
          >
          <el-button
            v-if="
              isAuth('work:clt:damage') &&
              Number(scope.row.state) === 2 &&
              (scope.row.nodeType == null || scope.row.nodeType === 'produce')
            "
            type="text"
            size="small"
            @click="damageTask(scope.row.nodeId, scope.row.productionId)"
            >报损</el-button
          >
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="sizeChangeHandle"
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-sizes="[10, 20, 50, 100]"
      :page-size="pageSize"
      :total="totalPage"
      layout="total, sizes, prev, pager, next, jumper"
    >
    </el-pagination>

    <el-dialog
      title="移交任务"
      width="30%"
      :visible.sync="transferDialogFormVisible"
    >
      <el-form
        :model="transferDialogForm"
        :rules="transferDialogFormRules"
        ref="transferDialogForm"
      >
        <!-- <el-form-item label="检验类型" prop="checkType" label-width="120px">
           <el-select v-model="transferDialogForm.checkType" placeholder="请选择检验类型">
            <el-option label="通过" value="1"></el-option>
            <el-option label="不通过" value="2"></el-option>
          </el-select>
        </el-form-item> -->
        <el-form-item label="移交类型" prop="transferType" label-width="120px">
          <el-select
            v-model="transferDialogForm.transferType"
            placeholder="请选择移交类型"
          >
            <el-option label="工作移交" value="1"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="移交用户"
          prop="transferUserId"
          label-width="120px"
        >
          <!--          <user-component v-model="transferDialogForm.transferUserId" :user-id.sync="transferDialogForm.transferUserId"></user-component>-->
          <el-select
            v-model="transferDialogForm.transferUserId"
            placeholder="请选择移交用户"
          >
            <el-option
              v-for="item in transferUserList"
              :key="item.userId"
              :label="item.name"
              :value="item.userId"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="移交说明"
          prop="transferExplain"
          label-width="120px"
        >
          <el-input
            v-model="transferDialogForm.transferExplain"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="transferDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="transferSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="检验任务"
      width="50%"
      :visible.sync="checkDialogFormVisible"
    >
      <el-form
        :model="checkDialogForm"
        :rules="checkDialogFormRules"
        ref="checkDialogForm"
      >
        <el-form-item
          v-if="
            checkDialogForm.checkType !== '1' && checkDialogForm.checkType !== 1
          "
          label="检验类型"
          prop="checkType"
          label-width="120px"
        >
          <el-select
            v-model="checkDialogForm.checkType"
            placeholder="请选择检验类型"
            style="width: 100%"
          >
            <el-option label="返回上一级" value="2"></el-option>
            <el-option label="报损" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item
          label="完成记录说明"
          prop="operationRecords"
          label-width="120px"
        >
          <el-input
            v-model="checkDialogForm.operationRecords"
            type="textarea"
            :rows="2"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="notes" label-width="120px">
          <el-input
            v-model="checkDialogForm.notes"
            type="textarea"
            :rows="2"
            placeholder="请输入备注"
          ></el-input>
        </el-form-item>
        <el-row v-if="checkDialogForm.checkType != null">
          <el-table
            :data="checkDialogForm.prodProductionRecordList"
            style="width: 100%"
          >
            <el-table-column prop="pageNo" label="页次/图区"> </el-table-column>
            <el-table-column prop="inspectionParam" label="检查参数">
            </el-table-column>
            <el-table-column prop="inspectionMethod" label="检验方法">
              <template slot-scope="scope">
                <span>{{
                  inspectionMethodOptions[scope.row.inspectionMethod]
                }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="allowValues" label="允许值">
            </el-table-column>
            <el-table-column prop="measureRecord1" label="实测记录1">
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'prodProductionRecordList.' +
                    scope.$index +
                    '.measureRecord1'
                  "
                  :rules="checkDialogFormRules.measureRecord1"
                  label-width="0px"
                >
                  <el-input v-model="scope.row.measureRecord1"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="measureRecord2" label="实测纪录2">
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'prodProductionRecordList.' +
                    scope.$index +
                    '.measureRecord2'
                  "
                  :rules="checkDialogFormRules.measureRecord2"
                  label-width="0px"
                >
                  <el-input v-model="scope.row.measureRecord2"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="remarks" label="备注">
              <template slot-scope="scope">
                <el-form-item
                  :prop="
                    'prodProductionRequireList.' + scope.$index + '.remarks'
                  "
                  label-width="0px"
                >
                  <el-input v-model="scope.row.remarks"></el-input>
                </el-form-item>
              </template>
            </el-table-column>
          </el-table>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button @click="checkDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="checkSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="操作损坏"
      width="30%"
      :visible.sync="damageDialogFormVisible"
    >
      <el-form
        :model="damageDialogForm"
        :rules="damageDialogFormRules"
        ref="damageDialogForm"
      >
        <el-form-item label="损坏原因" prop="damageReason" label-width="80px">
          <el-input
            v-model="damageDialogForm.damageReason"
            type="textarea"
            :rows="2"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="damageDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="damageSubmit">确 定</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="完成任务"
      width="30%"
      :visible.sync="finishDialogFormVisible"
    >
      <el-form
        :model="finishDialogForm"
        :rules="finishDialogFormRules"
        ref="finishDialogForm"
      >
        <el-form-item
          label="完成记录说明"
          prop="operationRecords"
          label-width="120px"
        >
          <el-input
            v-model="finishDialogForm.operationRecords"
            type="textarea"
            :rows="2"
            placeholder="请输入"
          ></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer">
        <el-button @click="finishDialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="finishSubmit">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 文件预览 -->
    <preview-component v-if="previewVisible" ref="preview" />
  </div>
</template>

<script>
import {
  getTaskList,
  startTask,
  transferTask,
  completeTask,
  checkTask,
  damageTask,
  getTaskDetail
} from '@/api/task'
import { workTypeMasterList } from '@/api/worktype'
import templateList from '../warehouse/template-list'
import PreviewComponent from '../common/preview-component'
import UserComponent from '@/views/modules/common/user-component'
export default {
  components: { UserComponent, PreviewComponent, templateList },
  name: 'work',
  computed: {
    userId: {
      get () {
        return this.$store.state.user.id
      }
    }
  },
  watch: {
    'dataForm.userId' (value) {
      this.opColVisible =
        Number(this.dataForm.state) !== 3 && value === this.userId
    },
    'dataForm.state' (value) {
      this.opColVisible = this.dataForm.userId
        ? Number(value) !== 3 && this.dataForm.userId === this.userId
        : Number(value) !== 3
    }
  },
  data () {
    return {
      previewVisible: false,
      addOrUpdateVisible: false,
      opColVisible: true,
      dataForm: {
        state: '1'
      },
      dataList: [],
      pageIndex: 1,
      pageSize: 10,
      totalPage: 0,
      dataListLoading: false,
      dataListSelections: [],
      optionsState: [
        {
          code: '1',
          value: '未开始'
        },
        {
          code: '2',
          value: '待操作'
        },
        {
          code: '3',
          value: '已完成'
        }
      ],
      transferDialogFormVisible: false,
      transferDialogForm: {},
      finishDialogFormVisible: false,
      finishDialogForm: {},
      finishDialogFormRules: {
        operationRecords: [
          { required: true, message: '完成记录说明不能为空', trigger: 'blur' }
        ]
      },
      transferUserList: [],
      transferDialogFormRules: {
        transferType: [
          { required: true, message: '请选择移交类型', trigger: 'blur' }
        ],
        transferUserId: [
          { required: true, message: '请选择移交用户', trigger: 'blur' }
        ]
      },
      checkDialogFormVisible: false,
      checkDialogForm: {
        checkType: '',
        operationRecords: '',
        notes: '',
        prodProductionRecordList: []
      },
      checkDialogFormRules: {
        operationRecords: [
          { required: true, message: '完成记录说明不能为空', trigger: 'blur' }
        ],
        checkType: [{ required: true, message: '请选择', trigger: 'blur' }],
        measureRecord1: [
          { required: true, message: '请输入', trigger: 'blur' }
        ],
        measureRecord2: [
          { required: true, message: '请输入', trigger: 'blur' }
        ]
      },
      damageDialogFormVisible: false,
      damageDialogForm: {},
      damageDialogFormRules: {
        damageReason: [{ required: true, message: '请输入', trigger: 'blur' }]
      },
      // 是否显示进度条列
      showProgress: true,
      inspectionMethodOptions: {
        1: '游标卡尺',
        2: '千分尺',
        3: '高度尺',
        4: '百分表',
        5: 'R规',
        6: '环规、塞规',
        7: '游标角度尺',
        8: '三坐标',
        9: '模具',
        10: '样板',
        11: '夹具',
        12: '目测',
        13: '组合测量',
        14: '精密测量',
        15: '敲击',
        16: '测厚仪',
        17: '其他'
      }
    }
  },
  created () {
    this.getDataList()
  },
  methods: {
    // 查询
    queryData () {
      this.pageIndex = 1
      this.showProgress = this.dataForm.state !== '2'
      this.getDataList()
    },
    // 获取数据列表
    getDataList () {
      this.dataListLoading = true
      let params = {
        current: this.pageIndex,
        size: this.pageSize,
        state: this.dataForm.state,
        userId: this.dataForm.userId ? this.dataForm.userId : null
      }
      getTaskList(params).then(({ data }) => {
        if (data && data.code === '200') {
          this.dataList = data.data.records
          this.totalPage = Number(data.data.total)
        } else {
          this.dataList = []
          this.totalPage = 0
        }
        this.dataListLoading = false
      })
    },
    // 每页数
    sizeChangeHandle (val) {
      this.pageSize = val
      this.pageIndex = 1
      this.getDataList()
    },
    // 当前页
    currentChangeHandle (val) {
      this.pageIndex = val
      this.getDataList()
    },
    // 多选
    selectionChangeHandle (val) {
      this.dataListSelections = val
    },
    // 开始
    startTask (taskId) {
      this.$confirm('是否开始任务?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          startTask({ taskId }).then(({ data }) => {
            if (data && data.code === '200') {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.getDataList()
            } else {
              this.$message({
                type: 'error',
                message: data.msg
              })
            }
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消'
          })
        })
    },
    // 移交
    transferTask (taskId, workTypeId) {
      this.transferDialogFormVisible = true
      this.transferDialogForm.taskId = taskId

      workTypeMasterList(workTypeId).then(({ data }) => {
        if (data && data.code === '200') {
          this.transferUserList = data.data
        }
      })
    },
    // 确认移交
    transferSubmit () {
      this.$refs['transferDialogForm'].validate((valid) => {
        if (valid) {
          transferTask(this.transferDialogForm).then(({ data }) => {
            if (data && data.code === '200') {
              this.$message({
                type: 'success',
                message: '移交成功!'
              })
              this.transferDialogFormVisible = false
              this.getDataList()
            } else {
              this.$message({
                type: 'error',
                message: data.msg
              })
            }
          })
        }
      })
    },
    // 完成
    completeTask (taskId) {
      this.finishDialogFormVisible = true
      this.finishDialogForm.taskId = taskId
    },
    // 确认完成
    finishSubmit () {
      this.$refs['finishDialogForm'].validate((valid) => {
        if (valid) {
          let submitData = this.finishDialogForm
          completeTask(submitData).then(({ data }) => {
            if (data && data.code === '200') {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.finishDialogFormVisible = false
              this.getDataList()
            } else {
              this.$message({
                type: 'error',
                message: data.msg
              })
            }
          })
        }
      })
    },
    // 检验
    checkTask (taskId, checkType) {
      this.checkDialogForm.taskId = taskId

      if (checkType === 1) {
        // 查询工艺详情
        getTaskDetail(this.checkDialogForm.taskId).then(({ data }) => {
          if (data && data.code === '200') {
            let list = data.data.prodProductionRequireList
            if (list && list.length > 0) {
              list.map((item) => {
                item.requireId = item.id
              })
            }
            this.checkDialogForm.prodProductionRecordList = list
          }
        })

        this.checkDialogForm.checkType = checkType
        this.passTask()
      } else {
        this.checkDialogForm.checkType = null
        this.refuseTask()
      }
    },
    // 通过
    passTask () {
      this.checkDialogFormVisible = true
    },
    // 不通过
    refuseTask () {
      this.checkDialogFormVisible = true
    },
    // 确认检验
    checkSubmit () {
      this.$refs['checkDialogForm'].validate((valid) => {
        if (valid) {
          let submitData = this.checkDialogForm
          // console.log(submitData);
          checkTask(submitData).then(({ data }) => {
            if (data && data.code === '200') {
              this.$message({
                type: 'success',
                message: '检验成功!'
              })
              this.checkDialogFormVisible = false
              this.getDataList()
            } else {
              this.$message({
                type: 'error',
                message: data.msg
              })
            }
          })
        }
      })
    },
    // 操作损坏
    damageTask (nodeId, productionId) {
      this.damageDialogFormVisible = true
      this.damageDialogForm.nodeId = nodeId
      this.damageDialogForm.productionId = productionId
    },
    // 确认操作损坏
    damageSubmit () {
      this.$refs['damageDialogForm'].validate((valid) => {
        if (valid) {
          let submitData = this.damageDialogForm
          damageTask(submitData).then(({ data }) => {
            if (data && data.code === '200') {
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.damageDialogFormVisible = false
              this.getDataList()
            } else {
              this.$message({
                type: 'error',
                message: data.msg
              })
            }
          })
        }
      })
    },
    // 预览
    previewFile (fileName, url) {
      this.previewVisible = true
      this.$nextTick(() => {
        this.$refs.preview.init(fileName, url)
      })
    },
    // 计算进度百分比，返回0到100的整数
    getPercentage (completeNum, totalNum) {
      completeNum = completeNum == null ? 0 : parseInt(completeNum)
      totalNum = totalNum == null ? 100 : parseInt(totalNum)
      if (totalNum === 0) {
        return 100
      }

      return (completeNum / totalNum).toFixed(2) * 100
    },
    // 用户选择
    userChanged (val) {
      this.dataForm.userId = val
      this.getDataList()
    }
  }
}
</script>

<style scoped></style>
