<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      v-model:page="page"
      v-model="form"
      ref="crud"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <!-- <template #testType="{row}">
        <span>{{row.testType == 0 ? '零件' : '试片'}}</span>
      </template> -->
      <template #jobType="{row}">
        <span v-if="row.jobType == 1">{{row.jobTypeWeekValue.split(',').length}}次/周</span>
        <span v-if="row.jobType == 2">{{row.jobTypeMonthValue.split(',').length}}次/月</span>
        <span v-if="row.jobType == 3">{{row.jobTypeYearValue.split(',').length}}次/年</span>
      </template>
      <template #menu-left>
        <el-button @click="handleAdd" type="primary">新增</el-button>
        <el-button type="danger" @click="handleDeletes">删 除</el-button>

        <el-button type="success" @click="handleUser">人员设置</el-button>
        <el-button type="primary" @click="handleCycle">批量设置周期</el-button>
        <el-button type="warning" @click="handleExport" plain>导出</el-button>
      </template>
      <template #menu-right>
        <el-button type="primary" @click="handleImport">导入</el-button>
      </template>
      <template #menu="scope">
        <el-button type="text" @click="handleView(scope.row, 'view')">详情</el-button>
        <el-button type="text" @click="handleEdit(scope.row, 'add')">编辑</el-button>
        <el-button type="text" @click="handleDelete(scope.row, 'add')">删除</el-button>
        <el-button type="text" @click="handleIssue(scope.row, 'add')">下发</el-button>
      </template>
    </avue-crud>
    <!-- 新增 编辑 详情 -->
    <addProjectCycleDialog :title="title" v-if="showDialog" :showDialog="showDialog" @closeDialog="closeDialog"
    :row="projectForm"></addProjectCycleDialog>
    <!-- 人员设置 -->
    <el-dialog append-to-body :title="title1" 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-item label="下发时间" prop="oneTimeGenDate" v-if="title1 == '任务下发'">
          <el-date-picker
            v-model="issueForm.oneTimeGenDate"
            style="width:100%"
            type="date"
            :clearable="false"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="请选择下发时间"
          />
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="issueDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitIssue">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 批量设置周期 -->
    <el-dialog append-to-body title="批量设置周期" v-model="cycleDialog" width="550px">
      <el-form ref="cycleForm" :model="cycleForm" label-width="80px" :rules="cycleRules">
        <el-form-item label="试验周期" prop="jobType">
            <el-select
              placeholder="请选择试验周期"
              v-model="cycleForm.jobType"
              style="width: 268px"
              @change="changeCycle1"
            >
              <el-option label="每周" :value="1"></el-option>
              <el-option label="每月" :value="2"></el-option>
              <el-option label="每年" :value="3"></el-option>
            </el-select>
          </el-form-item>
          <div style="margin-left: 80px" v-show="cycleForm.jobType == 1">
            <el-checkbox-group v-model="cycleForm.weekList">
              <el-checkbox label="周一" value="1" />
              <el-checkbox label="周二" value="2"></el-checkbox>
              <el-checkbox label="周三" value="3"></el-checkbox>
              <el-checkbox label="周四" value="4"></el-checkbox>
              <el-checkbox label="周五" value="5"></el-checkbox>
              <el-checkbox label="周六" value="6"></el-checkbox>
              <el-checkbox label="周日" value="7"></el-checkbox>
            </el-checkbox-group>
          </div>
          <div style="margin-left: 80px" v-show="cycleForm.jobType == 2">
            <div style="display: flex; align-items: center">
              <span>时间：每月</span>
              <el-select v-model="cycleForm.monthValue" style="width: 120px; margin: 0 5px">
                <el-option v-for="item in 31" :key="item" :label="item" :value="item"></el-option>
              </el-select>
              <span>日</span>
              <el-button style="margin-left: 10px" type="primary" circle @click="addMonth"
                ><el-icon> <Plus /> </el-icon
              ></el-button>
            </div>
            <div style="display: flex; flex-wrap: wrap; margin-top: 10px">
              <el-tag
                v-for="tag in cycleMonthTags"
                :key="tag"
                closable
                type="info"
                style="width: 62px; margin-right: 5px; margin-top: 10px"
                @close="closeMonthTag(tag, index)"
              >
                {{ tag }}
              </el-tag>
            </div>
            <div>
              <el-checkbox
                v-model="cycleForm.isPutOff"
                label="任务若遇周末或当月无该日期，顺延至下周一"
              />
            </div>
          </div>
          <div style="margin-left: 100px" v-show="cycleForm.jobType == 3">
            <div style="display: flex; align-items: center">
              <span>时间</span>
              <el-select v-model="cycleForm.yearMonth" style="width: 120px; margin: 0 5px">
                <el-option v-for="item in 12" :key="item" :label="item" :value="item"></el-option>
              </el-select>
              <span>月</span>
              <el-select v-model="cycleForm.yearDays" style="width: 120px; margin: 0 5px">
                <el-option v-for="item in 31" :key="item" :label="item" :value="item"></el-option>
              </el-select>
              <span>日</span>
              <el-button style="margin-left: 10px" type="primary" circle @click="addYears"
                ><el-icon> <Plus /> </el-icon
              ></el-button>
            </div>
            <div style="display: flex; flex-wrap: wrap; margin-top: 10px">
              <el-tag
                v-for="(tag, index) in cycleYearTags"
                :key="tag"
                closable
                type="info"
                style="width: 86px; margin-right: 5px; margin-top: 10px"
                @close="closeYearsTag(tag, index)"
              >
                {{ tag }}
              </el-tag>
            </div>
            <div>
              <el-checkbox
                v-model="cycleForm.isPutOff"
                label="任务若遇周末或当月无该日期，顺延至下周一"
              />
            </div>
          </div>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cycleDialog = false">取 消</el-button>
          <el-button type="primary" @click="submitCycle">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 导入 -->
    <basic-import v-if="isShowImport" title="导入" :isShow="isShowImport"
      showTips="请上传 .xls,.xlsx 标准格式文件,请导入数据后维护试验周期！"
      templateUrl="/blade-desk/QA/CycleTest/download-excel-template"
      templateName="试验项目周期模板.xlsx"
      importUrl="/blade-desk/QA/CycleTest/import-excel"
      @closeDialog="closeDialog"></basic-import>
  </basic-container>
</template>

<script>
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { downloadXls } from '@/utils/util';
import { getList, remove,issueTask,getUserList,setUser,setCycleBat,exportExcel } from '@/api/qualityManagement/periodicTesting/projectCycle.js';
import addProjectCycleDialog from './components/addProjectCycleDialog.vue'
import {dateFormat} from '@/utils/date'
import basicImport from '@/components/basic-import/main.vue'
export default {
  components:{
    addProjectCycleDialog,
    basicImport
  },
  data() {
    return {
      isShowImport: false,
      loading: false,
      data: [],
      projectForm: {},
      projectRules: {
        tpProject: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        testPieceTitle: [{ required: true, message: '请选择试验件', trigger: 'blur' }],
        tpStandard: [{ required: true, message: '请输入试验标准', trigger: 'blur' }],
        craftMan: [{ required: true, message: '请选择工艺员', trigger: 'blur' }],
        remDays: [{ required: true, message: '请选择超期提醒', trigger: 'blur' }],
        textCycle: [{ required: true, message: '请选择试验周期', trigger: 'blur' }],
      },
      form: {},
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0,
      },
      issueDialog: false,
      cycleDialog:false,
      cycleForm:{},
      cycleRules:{
        jobType: [{ required: true, message: '请选择试验周期', trigger: 'blur' }],
      },
      issueForm: {},
      formRules: {
        processUserId: [{ required: true, message: '请选择工艺员', trigger: 'blur' }],
      },
      title1: '任务下发',
      userData: [],
      selectionList: [],
      title: '新增',
      showDialog: false,
      monthTags: [],
      yearTags: [],
      cycleMonthTags:[],
      cycleYearTags:[],
      option: {
        tip: false,
        align: 'center',
        // size: 'medium',
        height: 'auto',
        calcHeight: 32,
        columnSort: true,
        searchShow: true,
        searchMenuSpan: 6,
        searchIcon: true,
        searchIndex: 3,
        tree: false,
        border: true,
        index: false,
        selection: true,
        viewBtn: false,
        delBtn: false,
        addBtn: false,
        editBtn: false,
        editBtnText: '修改',
        viewBtnText: '详情',
        addBtnIcon: ' ',
        viewBtnIcon: ' ',
        delBtnIcon: ' ',
        editBtnIcon: ' ',
        labelWidth: 120,
        menuWidth: 190,
        dialogWidth: 600,
        dialogClickModal: false,
        searchEnter: true,
        // filterBtn: true,
        searchShowBtn: false,
        // excelBtn: true,
        showOverflowTooltip: true,
        align: 'center',
        searchLabelPosition: 'left',
        searchGutter:24,
        searchSpan:6,
        menuAlign: 'left',
        gridBtn: false,
        searchMenuPosition: 'right',
        column: [
          {
            label: '镀种',
            prop: 'plateNames',
            search: false,
            sortable: true,
            filter: true,
            width: 150,
          },
          {
            label: '镀种',
            prop: 'plateId',
            type: 'select',
            hide: true,
            search: true,
            sortable: true,
            filter: true,
            width: 150,
            dicUrl:"/api/blade-desk/BA/Plating/listForSelectCycleTest",
            props:{
              label:'plating',
              value:'id'
            }
          },
          {
            label: '试验项目',
            prop: 'cycleTestItemName',
            search: false,
            type: 'select',
            sortable: true,
            filter: true,
            
            width: 200,
          },
          {
            label: '试验条件',
            prop: 'cycleTestItemCondition',
            search: true,
            sortable: true,
            filter: true,
            width: 200,
          },
          {
            label: '试验标准',
            prop: 'cycleTestStandardName',
            search: true,
            sortable: true,
            width: 200,
          },
          {
            label: '试验件',
            prop: 'testType',
            search: true,
            sortable: true,
            filter: true,
            width: 120,
            type: 'select',
            dicUrl:"/blade-system/dict/dictionary?code=testPiece",
            props:{
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '试验件材料',
            prop: 'testMat',
            search: false,
            sortable: true,
            filter: true,
            width: 180,
          },
          {
            label: '工艺员',
            prop: 'processUserId',
            search: true,
            sortable: true,
            filter: true,
            width: 160,
            type: 'select',
            dicUrl:'/blade-system/user/list-process-engineer',
            props:{
              label:"name",
              value:"id"
            }
          },
          {
            label: '试验周期',
            prop: 'jobType',
            search: false,
            sortable: true,
            filter: true,
            width: 120,
          },
          {
            label: '试验周期',
            prop: 'jobTypes',
            type: 'select',
            hide:true,
            search: true,
            sortable: true,
            filter: true,
            width: 120,
            dicData:[
              { label:"周",value:1 },
              { label:"月",value:2 },
              { label:"年",value:3 },
            ]
          },
          {
            label: '最小试验数量',
            prop: 'minDoTestCount',
            search: false,
            sortable: true,
            filter: true,
            width: 140,
          },
          {
            label: '试验项目',
            prop: 'cycleTestItemId',
            search: true,
            searchOrder: 1,
            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: 'genBefore',
            search: false,
            sortable: true,
            filter: true,
            width: 200,
          },
          {
            label: '超期提醒天数',
            prop: 'remind',
            search: false,
            sortable: true,
            filter: true,
            width: 200,
          },
          {
            label: '更新时间',
            prop: 'updateTime',
            search: false,
            sortable: true,
            filter: true,
            width: 200,
          },
        ],
      },
    };
  },
  mounted() {
    this.getUsers()
  },
  methods: {
    // 点击导入按钮
    handleImport() {
      this.isShowImport = true
    },
    // 获取工艺员列表
    getUsers(){
      getUserList().then(res =>{
        this.userData = res.data.data
      })
    },
    closeDialog(){
      this.showDialog = false;
      this.isShowImport = false
      this.onLoad(this.page)
    },
    // 点击详情按钮
    handleView(row) {
      this.projectForm = row;
      this.title = '详情';
      this.showDialog = true;
    },
    // 点击编辑按钮
    handleEdit(row) {
      this.projectForm = row;
      this.title = '编辑';
      if (this.projectForm.textCycle == '3') {
        this.yearTags = this.projectForm.tags;
      } else if (this.projectForm.textCycle == '2') {
        this.monthTags = this.projectForm.tags;
      } else {
        this.projectForm.weekList = this.projectForm.tags;
      }
      this.showDialog = true;
    },
    // 点击下发按钮
    handleIssue(row) {
      this.title1 = '任务下发';
      let date = dateFormat(new Date(),'yyyy-MM-dd')
      this.issueForm = {}
      this.issueForm.cycleTestId = row.id
      // this.issueForm.oneTimeGenDate = date
      this.issueForm.processUserId = row.processUserId
      this.issueDialog = true;
    },
    // 点击上方删除按钮，多条删除
    handleDeletes() {
      if (this.selectionList.length == 0) {
        this.$message.error('请至少选择一条数据!');
      } else {
        this.$confirm('确定删除所选数据?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }).then(() => {
          remove(this.selectionList.map(item => item.id).join(',')).then(res =>{
            if(res.data.code == 200){
              this.$message.success('删除成功')
              this.onLoad(this.page)
            }
          })
        });
      }
    },

    // 点击人员配置按钮
    handleUser() {
      if (this.selectionList.length == 0) {
        this.$message.error('请至少选择一条数据!');
      } else {
        this.title1 = '人员设置';
        this.issueDialog = true;
        this.issueForm = {}
      }
    },
    // 批量设置周期
    handleCycle(){
      if (this.selectionList.length == 0) {
        this.$message.error('请至少选择一条数据!');
      } else {
        this.cycleForm = {}
        this.cycleMonthTags = []
        this.cycleYearTags = []
        this.cycleDialog = true
      }
    },
    // 导出
    handleExport(){
      let param = {
        ...this.query,
        jobType:this.query && this.query.jobTypes && this.query.jobTypes
      }

      const { jobTypes, ...validData } = param;
      this.$confirm('是否导出试验项目周期数据?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        NProgress.start();
        exportExcel(validData).then(res =>{
          downloadXls(res.data, `试验周期表${this.$dayjs().format('YYYY-MM-DD')}.xlsx`);
          NProgress.done();
        })
      })
    },
    // 点击删除按钮
    handleDelete(row) {
      this.$confirm('确定删除此条数据?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }).then(() => {
        remove(row.id).then(res =>{
          if(res.data.code == 200){
            this.$message.success('删除成功')
            this.onLoad(this.page)
          }
        })
      });
    },
    // 点击新增按钮
    handleAdd() {
      this.title = '新增';
      this.showDialog = true;
      this.projectForm = {};
      this.monthTags = [];
      this.yearTags = [];
      this.$refs.form.resetFields();
    },
    // 切换周期
    changeCycle() {
      this.projectForm.monthValue = '';
      this.projectForm.weekList = [];
      this.monthTags = [];
      this.projectForm.yearMonth = '';
      this.projectForm.yearDays = '';
      this.yearTags = [];
    },
    // 切换周期
    changeCycle1() {
      this.cycleForm.monthValue = '';
      this.cycleForm.weekList = [];
      this.cycleMonthTags = [];
      this.cycleForm.yearMonth = '';
      this.cycleForm.yearDays = '';
      this.cycleYearTags = [];
    },
    // 添加月份日期
    addMonth() {
      let value = this.cycleForm.monthValue + '日';
      if (this.cycleMonthTags.find(item => item == value)) return;
      this.cycleMonthTags.push(this.cycleForm.monthValue + '日');
    },
    // 添加年份日期
    addYears() {
      let value = this.cycleForm.yearMonth + '月' + this.cycleForm.yearDays + '日';
      console.log('value--------------',value)
      if (this.cycleYearTags.find(item => item == value)) return;
      if (this.cycleForm.yearMonth == '' || this.cycleForm.yearDays == '') return;
      this.cycleYearTags.push(this.cycleForm.yearMonth + '月' + this.cycleForm.yearDays + '日');
    },
    // 删除月份日期
    closeMonthTag(item, index) {
      this.cycleMonthTags = this.cycleMonthTags.filter(tags => tags != item);
    },
    // 删除年份日期
    closeYearsTag(item, index) {
      this.cycleYearTags = this.cycleYearTags.filter(tags => tags != item);
    },
    // 新增确定按钮
    submitForm() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.showDialog = false;
        }
      });
    },
    // 下发弹窗确定按钮
    submitIssue() {
      this.$refs.issueForm.validate(valid => {
        if (valid) {
          if(this.title1 == '任务下发'){
            console.log('issueForm-------------',this.issueForm)
            issueTask(this.issueForm).then(res =>{
              console.log('res---------------',res)
              this.$message.success('下发成功')
              this.onLoad(this.page)
            })
          }else{
            setUser({
              ids:this.selectionList.map(item => item.id).join(','),
              processUserId:this.issueForm.processUserId
            }).then(res =>{
              if(res.data.code == 200){
                this.$message.success('设置成功')
                this.onLoad(this.page)
              }
            })
          }
          this.issueDialog = false;
        }
      });
    },
    // 批量设置周期
    submitCycle(){
      this.$refs.cycleForm.validate(valid =>{
        if(valid){
          let monthArr = []
          let yearArr = []
            if(this.cycleForm.jobType == 2){
              if(this.cycleMonthTags.length == 0){
                this.$message.error('请选择日期')
                return
              }
              monthArr = this.cycleMonthTags.map(str => {
                // 提取数字部分（匹配连续的数字）
                const num = str.match(/\d+/)?.[0] || '0';
                // 补零到两位
                return num.padStart(2, '0');
              });
            }
            if(this.cycleForm.jobType == 1){
              if(this.cycleForm.weekList.length == 0){
                this.$message.error('请选择日期')
                return
              }
            }
            if(this.cycleForm.jobType == 3){
              if(this.cycleYearTags.length == 0){
                this.$message.error('请选择日期')
                return
              }
              yearArr =  this.cycleYearTags.map(str => {
                // 使用正则匹配“数字 + 月 + 数字 + 日”结构
                const match = str.match(/(\d+)月(\d+)日/);
                if (!match) return '0000'; // 防御性处理：格式不符时返回默认值

                const month = match[1].padStart(2, '0');
                const day = match[2].padStart(2, '0');
                return month + day;
              });
            }

            let params = {
              ids:this.selectionList.map(item => item.id).join(','),
              jobType:this.cycleForm.jobType,
              jobTypeWeekValue:this.cycleForm.jobType == 1 ? this.cycleForm.weekList.join(',') : '',
              jobTypeMonthValue:this.cycleForm.jobType == 2 ? monthArr.join(',') : '',
              jobTypeYearValue:this.cycleForm.jobType == 3 ? yearArr.join(',') : '',
              isPutOff:this.cycleForm.isPutOff ? 1 : 0,
            }
            console.log('params===============',params)
            setCycleBat(params).then(res =>{
              if(res.data.code == 200){
                this.$message.success('设置成功')
                this.cycleDialog = false
                this.onLoad(this.page)
              }
            })
        }
      })
    },
    // 多选
    selectionChange(list) {
      this.selectionList = list;
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    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 = {
        ...this.query,
        jobType:this.query && this.query.jobTypes && this.query.jobTypes
      }

      const { jobTypes, ...validData } = param;
      console.log('validData----------',validData)

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

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

<style></style>
