<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model:page="page"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template #menu-left>
        <el-button @click="handleIssue" type="primary" v-if="permission.issue_btn"> 转派 </el-button>
        <el-button type="warning" plain @click="handleExport">导出</el-button>
      </template>
      <template #menu-right="{ size }">
        <el-button type="warning" plain @click="handleSearch(1)">临期</el-button>
        <el-button type="danger" plain @click="handleSearch(2)">超期</el-button>
      </template>
      <template #menu="scope">
        <el-button type="text" @click="handleView(scope.row, 'view')" v-if="permission.detail_task">详情</el-button>
        <el-button type="text" @click="issueRow(scope.row, 'add')" v-show="scope.row.status == 1 && permission.issue_btn">
          下发
        </el-button>
        <el-button
          type="text"
          v-show="scope.row.status == 3 && permission.fill_task"
          @click="handleWrite(scope.row, 'drug')"
          >填报</el-button
        >
        <el-button
          type="text"
          v-show="scope.row.status == 2 && permission.receive_task"
          @click="handleReceive(scope.row, 'check')"
          >接收</el-button
        >
        <!-- <el-button type="text" v-show="scope.row.trStatus == 5"  @click="handleReport(scope.row,'check')">报告</el-button> -->
      </template>
      <template #countDayToPlanedFinish="{ row }">
        <div
          :style="{
            width: '100%',
            height: '49px',
            lineHeight: '49px',
            background:
              row.countDayToPlanedFinish != '' ?
              row.countDayToPlanedFinish <= 0
                ? '#ff0000'
                : row.countDayToPlanedFinish >= 7
                ? '#fffd00'
                : row.countDayToPlanedFinish > 0 && row.countDayToPlanedFinish < 7
                ? '#ffad00'
                : '#fff' : '#fff',
          }"
        >
          {{ row.countDayToPlanedFinish }}
        </div>
      </template>
    </avue-crud>
    <el-dialog append-to-body title="任务下发" v-model="issueDialog" width="550px">
      <el-form ref="issueForm" :model="issueForm" label-width="80px" :rules="formRules">
        <el-form-item label="工艺员" prop="processUserId">
          <el-select v-model="issueForm.processUserId">
            <el-option
              v-for="item in userData"
              :key="item.id" :label="item.name" :value="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="issueDialog = false">取 消</el-button>
          <el-button type="primary" @click="submit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <el-dialog append-to-body title="试验填报" v-model="writeDialog" width="550px">
      <el-form ref="writeForm" :model="writeForm" label-width="120" :rules="writeRules">
        <el-form-item label="是否进行试验" prop="isDone">
          <el-radio-group v-model="writeForm.isDone">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="2">否</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="试验时间" prop="testDate" v-if="writeForm.isDone == 1">
          <el-date-picker v-model="writeForm.testDate" value-format="YYYY-MM-DD" format="YYYY-MM-DD" type="date" placeholder="请选择试验时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="试验结果" prop="testResult" v-if="writeForm.isDone == 1">
          <el-upload
            class="upload-demo"
            action="/api/blade-resource/oss/endpoint/put-file-attach"
            :on-success="handleSuccess"
            :on-remove="handleRemove"
            multiple
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList"
            accept=".rar,.zip,.doc,.docx,.pdf,.jpg"
          >
            <div>
              <el-button type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                支持扩展名：.rar .zip .doc .docx .pdf .jpg..
              </div>
            </div>
          </el-upload>
        </el-form-item>
        <el-form-item label="未试验原因" prop="reasonForNo" v-if="writeForm.isDone == 2">
          <el-input type="textarea" v-model="writeForm.reasonForNo" placeholder="请填写未试验原因"></el-input>
        </el-form-item>
        <el-form-item label="超期原因" prop="reasonForOut" v-if="writeForm.flagOut == 1">
          <el-input type="textarea" v-model="writeForm.reasonForOut" placeholder="请填写超期原因"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="writeDialog = false">取 消</el-button>
          <el-button type="primary" @click="writeSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <view-dialog
      v-if="viewDialog"
      :show-dialog="viewDialog"
      :row-id="rowId"
      :row-obj="rowObj"
      @closeDialog="closeDialog"
    ></view-dialog>
  </basic-container>
</template>

<script>
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { exportBlob } from '@/api/common';
import { downloadXls } from '@/utils/util';
import { mapGetters } from 'vuex';
import website from '@/config/website';
import { getToken } from '@/utils/auth';
import {dateFormat} from '@/utils/date'
import viewDialog from './components/viewDialog.vue';
import { getTaskList, remove,issueTask,acceptTask,issueAllTask,writeTask,exportExcel } from '@/api/qualityManagement/periodicTesting/testTask.js';
import { getUserList} from '@/api/qualityManagement/periodicTesting/projectCycle.js';

export default {
  components: {
    viewDialog,
  },
  data() {
    var checkFile = (rule, value, callback) => {
      if (this.fileList.length == 0) {
        return callback(new Error('请上传文件'));
      } else {
        callback();
      }
    };
    return {
      data: [],
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      viewDialog: false,
      fileList: [],
      writeForm: {
      },
      // writeRules: {
      //   isDone: [{ required: true, message: '请选择是否进行试验', trigger: 'blur' }],
      //   testDate: [{ required: true, message: '请选择试验时间', trigger: 'blur' }],
      //   testResult: [{ validator: checkFile, trigger: 'blur' }],
      // },
      showDialog: false,
      rowId: '',
      rowObj: {},
      issueDialog: false,
      form: {},
      formRules: {
        processUserId: [{ required: true, message: '请选择工艺员', trigger: 'blur' }],
      },
      userData: [],
      writeDialog: false,
      query: {},
      loading: true,
      issueForm: {},
      option: {
        tip: false,
        align: 'center',
        size: 'medium',
        height:'auto',
        searchLabelWidth:120,
        simplePage: true,
        searchShow: true,
        searchMenuSpan: 6,
        searchIcon: true,
        searchIndex: 3,
        tree: false,
        border: true,
        selection: true,
        viewBtn: false,
        editBtn:false,
        addBtn:false,
        delBtn: false,
        editBtnText: '修改',
        viewBtnText:'详情',
        labelWidth: 120,
        menuWidth: 120,
        dialogWidth: 1200,
        dialogClickModal: false,
        searchEnter: true,
        excelBtn: false,
        filterBtn: true,
        searchShowBtn: false,
        excelBtn: true,
        index: false,
        showOverflowTooltip: true,
        searchLabelPosition:'left',
        searchLabelPosition:'left',
        searchGutter:24,
        searchSpan:6,
        menuAlign: 'left',
        gridBtn:false,
        searchMenuPosition:'right',
        addBtnIcon: ' ',
        viewBtnIcon: ' ',
        delBtnIcon: ' ',
        editBtnIcon: ' ',
        column: [
          {
            label: '任务编号',
            prop: 'code',
            search: true,
            sortable: true,
            filter: true,
            addDisplay: false,
            editDisplay: false,
            viewDisplay: false,
            span: 24,
            width: 200,
            rules: [
              {
                required: true,
                message: '请输入任务编号',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '试验项目',
            prop: 'cycleTestItemId',
            searchOrder: 3,
            search: true,
            hide:true,
            type: 'select',
            sortable: true,
            filter: true,
            width: 200,
            dicUrl:'/api/blade-desk/QA/CycleTestItem/listForSelect',
            props: { label: 'name', value: 'id' },
            dicFormatter: (res) => {
              return res.data
            },
          },
          {
            label: '试验项目',
            prop: 'cycleTestItemName',
            search: false,
            type: 'select',
            sortable: true,
            filter: true,
            width: 200,
          },
          // {
          //   label: '试验项目',
          //   prop: 'tpId',
          //   sortable: true,
          //   type: 'select',
          //   filter: true,
          //   span: 24,
          //   width: 200,
          //   search: true,
          //   rules: [
          //     {
          //       required: true,
          //       message: '请输入试验项目',
          //       trigger: 'blur',
          //     },
          //   ],
          //   props: {
          //     label: 'tpProject',
          //     value: 'tpId',
          //   },
          //   dicData: [
          //     {
          //       deleted: false,
          //       keyValue: 1,
          //       tpCondition: '96小时',
          //       tpId: 1,
          //       tpProject: '盐雾试验',
          //     },
          //     {
          //       deleted: false,
          //       keyValue: 21,
          //       tpCondition: '68小时',
          //       tpId: 21,
          //       tpProject: '盐雾试验1',
          //     },
          //   ],
          // },
          {
            label: '试验条件',
            prop: 'cycleTestItemCondition',
            search: true,
            sortable: true,
            filter: true,
            span: 24,
            width: 200,
            rules: [
              {
                required: true,
                message: '请输入试验条件',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '试验标准',
            prop: 'cycleTestStandardName',
            type: 'textarea',
            search: true,
            sortable: true,
            filter: true,
            span: 24,
            width: 200,
            rules: [
              {
                required: true,
                message: '请输入试验标准',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '试验件',
            prop: 'testType',
            type: 'select',
            search: true,
            sortable: true,
            filter: true,
            span: 24,
            width: 200,
            dicUrl:'/blade-system/dict/dictionary?code=testPiece',
            props: { label: 'dictValue', value: 'dictKey' },
            dicFormatter: (res) => {
              return res.data
            },
          },
          {
            label: '临期天数',
            prop: 'countDayToPlanedFinish',
            search: true,
            sortable: true,
            editDisplay: false,
            filter: true,
            addDisplay: false,
            span: 24,
            width: 200,
            rules: [
              {
                required: true,
                message: '请输入临期天数',
                trigger: 'blur',
              },
            ],
          },
          
          // {
          //     label: '试验员',
          //     prop: 'mecMan',
          //     search: false,
          //     sortable: true,
          //     editDisplay:false,
          //     filter: true,
          //     addDisplay:false,
          //     span: 24,
          //     width:200,
          //     rules: [
          //         {
          //             required: true,
          //             message: '请输入试验员',
          //             trigger: 'blur',
          //         },
          //     ],
          // },
          {
            label: '状态',
            prop: 'status',
            searchOrder: 2,
            search: true,
            type: 'select',
            sortable: true,
            editDisplay: false,
            filter: true,
            addDisplay: false,
            span: 24,
            width: 200,
            rules: [
              {
                required: true,
                message: '请选择状态',
                trigger: 'blur',
              },
            ],
            dicUrl:'/blade-system/dict/dictionary?code=CycleTestTask-Status',
            props: { label: 'dictValue', value: 'dictKey' },
            dicFormatter: (res) => {
              return res.data
            },
            // dicData: [
            //   { label: '待下发', value: 1 },
            //   { label: '待接收', value: 2 },
            //   { label: '待试验', value: 3 },
            //   { label: '已超期', value: 4 },
            //   { label: '已完成', value: 5 },
            // ],
          },
          {
            label:'超期原因',
            prop:"reasonForOut",
            span: 24,
            width: 200,
          },
          {
            label: '工艺员',
            prop: 'processUserName',
            search: true,
            sortable: true,
            filter: true,
            span: 24,
            width: 200,
            // dicUrl: '/blade-system/user/page?current=1&&size=99999',
            props: {
              label: 'name',
              value: 'id',
              res: 'data.records',
            },
          },
          {
            label: '任务生成时间',
            prop: 'genDatetime',
            type:"date",
            searchOrder: 1,
            finishTime: '',
            search: true,
            searchRange: true,
            sortable: true,
            editDisplay: false,
            filter: true,
            addDisplay: false,
            span: 24,
            searchLabelWidth: 120,
            width: 200,
            rules: [
              {
                required: true,
                message: '请输入任务生成时间',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '任务下发时间',
            prop: 'issueDate',
            type:"date",
            searchRange: true,
            search: true,
            sortable: true,
            searchOrder: 1,
            editDisplay: false,
            filter: true,
            addDisplay: false,
            span: 24,
            width: 200,
            rules: [
              {
                required: true,
                message: '请输入任务下发时间',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '任务接收时间',
            prop: 'acceptDate',
            type:"date",
            searchRange: true,
            searchOrder: 1,
            search: true,
            sortable: true,
            editDisplay: false,
            filter: true,
            addDisplay: false,
            span: 24,
            width: 200,
            rules: [
              {
                required: true,
                message: '请输入任务接收时间',
                trigger: 'blur',
              },
            ],
          },
          {
            label: '任务完成时间',
            prop: 'finishDate',
            type:"date",
            searchRange: true,
            searchOrder: 1,
            search: true,
            sortable: true,
            editDisplay: false,
            filter: true,
            addDisplay: false,
            span: 24,
            width: 200,
            rules: [
              {
                required: true,
                message: '请输入任务完成时间',
                trigger: 'blur',
              },
            ],
          },
        ],
      },
      selectionList: [],
      dialogType: '',
      issueType:'one',
      filterType:''
    };
  },
  computed: {
    ...mapGetters(['permission']),
    writeRules(){
      const rules = {
        isDone: [{ required: true, message: '请选择是否进行试验', trigger: 'change' }],
        testDate:[],
        testResult:[],
        reasonForNo:[],
      };
      console.log('this.writeForm.isDone-------------',this.writeForm.isDone)
      if (this.writeForm.isDone == 1) {
        rules.testDate = [{ required: true, message: '请选择试验时间', trigger: 'blur' }];
        rules.testResult = [
          { required: true, message: '请上传文件', trigger: 'blur' },
          { validator: this.checkFile, trigger: 'blur' }
          ];
        rules.reasonForNo = []
      } else {
        rules.testDate = []; // 非必填
        rules.testResult = []; // 非必填
        rules.reasonForNo = [{ required: true, message: '请填写未试验原因', trigger: 'blur' }]
      }
      if(this.writeForm.flagOut == 1){
        rules.reasonForOut = [{ required: true, message: '请填写超期原因', trigger: 'blur' }];
      }else{
        rules.reasonForOut = [];
      }
      return rules;
    },
  },
  mounted() {
    console.log('permission--------------',this.permission)
    this.getUsers()
  },
  methods: {
    getUsers(){
      getUserList('1993624442365915137').then(res =>{
        this.userData = res.data.data
      })
    },
    // 文件上传完成
    handleSuccess(response, file, fileList) {
      this.fileList.push(response.data);
      this.writeForm.testResult = this.fileList.map(item => item.attachId).join(',')
    },
    // 文件删除
    handleRemove(file, fileList) {
      this.fileList = fileList;
      this.writeForm.testResult = fileList
    },
    handleExceed(){
      this.$message.error('试验结果最多上传一个')
    },
    // 查看详情
    handleView(row, type) {
      this.rowId = row.id;
      this.rowObj = row;
      this.viewDialog = true;
    },
    // 关闭弹窗
    closeDialog() {
      this.viewDialog = false;
    },
    // 多选
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    rowUpdate(row, index, done, loading) {},
    rowSave(row, done, loading) {},
    // 报告
    handleReport() {},
    // 填报
    handleWrite(row) {
      this.writeForm = {
        id:row.id,
        flagOut:row.flagOut
      };
      this.fileList = [];
      this.writeDialog = true;
      this.$refs.writeForm.resetFields();
    },
    // 批量下发
    handleIssue() {
      if (this.selectionList.length == 0) {
        this.$message.error('请至少选择一条数据');
        return
      } 

      if(this.selectionList.find(item => item.status != 2)){
        this.$message.error('请选择状态为【待接收】的数据')
        return
      }
      this.issueType = 'all'
      this.issueForm = {}
      this.issueDialog = true;
    },

    // 导出
    handleExport(){
      let param = {
        ...this.query,
        genDatetimeStart:this.query.genDatetime && this.query.genDatetime.length != 0 && dateFormat(this.query.genDatetime[0],"yyyy-MM-dd"),
        genDatetimeEnd:this.query.genDatetime && this.query.genDatetime.length != 0 && dateFormat(this.query.genDatetime[1],"yyyy-MM-dd"),
        issueDateStart:this.query.issueDate && this.query.issueDate.length != 0 && dateFormat(this.query.issueDate[0],"yyyy-MM-dd"),
        issueDateEnd:this.query.issueDate && this.query.issueDate.length != 0 && dateFormat(this.query.issueDate[1],"yyyy-MM-dd"),
        acceptDateStart:this.query.acceptDate && this.query.acceptDate.length != 0 && dateFormat(this.query.acceptDate[0],"yyyy-MM-dd"),
        acceptDateEnd:this.query.acceptDate && this.query.acceptDate.length != 0 && dateFormat(this.query.acceptDate[1],"yyyy-MM-dd"),
        finishDateStart:this.query.finishDate && this.query.finishDate.length != 0 && dateFormat(this.query.finishDate[0],"yyyy-MM-dd"),
        finishDateEnd:this.query.finishDate && this.query.finishDate.length != 0 && dateFormat(this.query.finishDate[1],"yyyy-MM-dd"),
        dayToPlanedFinish:this.query.countDayToPlanedFinish && this.query.countDayToPlanedFinish
      }
      const { genDatetime,issueDate,acceptDate,finishDate,countDayToPlanedFinish, ...validData } = param;
      this.$confirm('是否导出周期性试验任务数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        NProgress.start();
        exportExcel(validData).then(res => {
          console.log('res===============',res)
          downloadXls(res.data, `试验任务表${this.$dayjs().format('YYYY-MM-DD')}.xlsx`);
          NProgress.done();
        });
      })
    },
    // 临期超期筛选数据
    handleSearch(val){
      this.page.currentPage = 1
      this.filterType = val
      this.onLoad(this.page)
    },
    // 单个下发
    issueRow(row) {
      this.issueType = 'one'
      this.issueDialog = true;
      this.issueForm.id = row.id
      this.issueForm.processUserId = row.processUserId
    },
    // 接收
    handleReceive(row) {
      this.$confirm('确定接收此项任务?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        acceptTask({id:row.id}).then(res =>{
          if(res.data.code == 200){
            this.$message.success('接收成功')
            this.onLoad(this.page)
          }
        })
      });
    },
    writeSubmit() {
      this.$refs.writeForm.validate(valid => {
        if (valid) {
          let params ={
            id:this.writeForm.id,
            isDone:this.writeForm.isDone,
            testDate:this.writeForm.isDone == 1 ? this.writeForm.testDate : '',
            testAttachId:this.writeForm.isDone == 1 ? this.fileList.map(item => item.attachId).join(',') : '',
            reasonForNo:this.writeForm.isDone == 2 ? this.writeForm.reasonForNo ? this.writeForm.reasonForNo : '' : '',
            reasonForOut:this.writeForm.flagOut == 1 && this.writeForm.reasonForOut
          }
          console.log('prams----------',params)
          writeTask(params).then(res =>{
            if(res.data.code == 200){
              this.$message.success('填报成功')
              this.writeDialog = false;
              this.writeForm = {}
              this.onLoad(this.page)
            }
          })
        }
      });
    },
    searchReset() {
      this.query = {};
      this.filterType = ''
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.filterType = ''
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    rowDel(row, index, done) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {});
    },
    // 下发
    submit() {
      this.$refs.issueForm.validate(valid => {
        if (valid) {
          if(this.issueType == 'one'){
            issueTask(this.issueForm).then(res =>{
              if(res.data.code == 200){
                this.$message.success('下发成功')
                this.issueDialog = false
                this.onLoad(this.page)
              }
            })
          }else{
            issueAllTask({
              ids:this.selectionList.map(item => item.id).join(','),
              processUserId:this.issueForm.processUserId
            }).then(res =>{
              if(res.data.code == 200){
                this.$message.success('下发成功')
                this.issueDialog = false
                this.onLoad(this.page)
              }
            })
          }
        }
      });
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;

      let param = {
        ...params,
        genDatetimeStart:params.genDatetime && params.genDatetime.length != 0 && dateFormat(params.genDatetime[0],"yyyy-MM-dd"),
        genDatetimeEnd:params.genDatetime && params.genDatetime.length != 0 && dateFormat(params.genDatetime[1],"yyyy-MM-dd"),
        issueDateStart:params.issueDate && params.issueDate.length != 0 && dateFormat(params.issueDate[0],"yyyy-MM-dd"),
        issueDateEnd:params.issueDate && params.issueDate.length != 0 && dateFormat(params.issueDate[1],"yyyy-MM-dd"),
        acceptDateStart:params.acceptDate && params.acceptDate.length != 0 && dateFormat(params.acceptDate[0],"yyyy-MM-dd"),
        acceptDateEnd:params.acceptDate && params.acceptDate.length != 0 && dateFormat(params.acceptDate[1],"yyyy-MM-dd"),
        finishDateStart:params.finishDate && params.finishDate.length != 0 && dateFormat(params.finishDate[0],"yyyy-MM-dd"),
        finishDateEnd:params.finishDate && params.finishDate.length != 0 && dateFormat(params.finishDate[1],"yyyy-MM-dd"),
        dayToPlanedFinish:params.countDayToPlanedFinish && params.countDayToPlanedFinish
      }
      const { genDatetime,issueDate,acceptDate,finishDate,countDayToPlanedFinish, ...validData } = param;
      console.log('validData----------',validData)

      getTaskList({
        current:this.page.currentPage,
        size:this.page.pageSize,
        ...validData,
        filterType:this.filterType
      }).then(res => {
        this.data = res.data.data.records;

        this.loading = false;
        this.page.total = res.data.data.total
        // this.selectionClear();
      });
    },
  },
};
</script>

<style></style>
