<template>
  <el-dialog
    :title="title"
    append-to-body
    :modelValue="openShow"
    width="70%"
    @close="closeDialog"
  >
    <el-form
      ref="form"
      :model="projectForm"
      :rules="projectRules"
      label-width="120px"
      v-show="title == '新增' || title == '编辑'"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="项目名称：" prop="cycleTestItemId">
            <el-select filterable v-model="projectForm.cycleTestItemId" placeholder="请选择项目" @change="tpProjectChange" value-key="id">
              <el-option v-for="(item,index) in  projectOption" :key="index" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="试验条件：" prop="cycleTestItemCondition">
            <el-input
              disabled
              v-model="projectForm.cycleTestItemCondition"
              placeholder="请输入试验条件"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="试验标准：" prop="cycleTestStandardName">
            <el-input
              disabled
              v-model="projectForm.cycleTestStandardName"
              placeholder="请输入试验标准"
            ></el-input>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="镀种：" prop="plateId">
            <el-select v-model="projectForm.plateId">
              <el-option v-for="item in plateData" :key="item.id"  :label="item.plate" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="试验件：" prop="testType">
            <el-select v-model="projectForm.testType" placeholder="请选择试验件">
              <el-option v-for="item in pieceList" :key="item.id" :label="item.dictValue" :value="item.dictKey"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="试验件材料：" prop="testMat">
            <el-input v-model="projectForm.testMat" placeholder="请输入试验件材料"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="最小试验数量：" prop="minDoTestCount">
             <el-input-number
              v-model="projectForm.minDoTestCount"
              controls-position="right"
              :min="1"
            >
            </el-input-number>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="工艺员：" prop="processUserId">
            <el-select v-model="projectForm.processUserId" placeholder="请选择工艺员">
              <el-option v-for="item in userData" :key="item.id" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :span="8">
          <el-form-item label="试验时长：" prop="testDuration">
            <el-input-number
              v-model="projectForm.testDuration"
              controls-position="right"
              @change="handleChange"
              :min="1"
            >
            </el-input-number>
            <span style="margin-left: 5px">天</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="提前下发：" prop="genBefore">
            <el-input-number
              v-model="projectForm.genBefore"
              controls-position="right"
              @change="handleChange"
              :min="1"
            >
            </el-input-number>
            <span style="margin-left: 5px">天</span>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="临期提醒：" prop="remind">
            <el-input-number
              v-model="projectForm.remind"
              controls-position="right"
              @change="handleChange"
              :min="projectForm.testDuration"
            >
            </el-input-number>
            <span style="margin-left: 5px">天</span>
          </el-form-item>
        </el-col>

        <el-col :span="10">
          <el-form-item label="试验周期" prop="jobType">
            <el-select
              placeholder="请选择试验周期"
              v-model="projectForm.jobType"
              style="width: 268px"
              @change="changeCycle"
            >
              <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: 100px" v-show="projectForm.jobType == 1">
            <el-checkbox-group v-model="projectForm.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: 100px" v-show="projectForm.jobType == 2">
            <div style="display: flex; align-items: center">
              <span>时间：每月</span>
              <el-select v-model="projectForm.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 monthTags"
                :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="projectForm.isPutOff"
                label="任务若遇周末或当月无该日期，顺延至下周一"
              />
            </div>
          </div>
          <div style="margin-left: 100px" v-show="projectForm.jobType == 3">
            <div style="display: flex; align-items: center">
              <span>时间</span>
              <el-select v-model="projectForm.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="projectForm.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 yearTags"
                :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="projectForm.isPutOff"
                label="任务若遇周末或当月无该日期，顺延至下周一"
              />
            </div>
          </div>
        </el-col>
      </el-row>
    </el-form>
    <div v-show="title == '详情'">
      <div style="font-weight: 550; margin-bottom: 20px">检测信息</div>
      <el-row :gutter="20" style="padding: 5px 0">
        <el-col :span="6"
          >镀种：{{projectForm.plateName}}</el-col
        >
        <el-col :span="6">试验件：{{ projectForm.testTypeName }}</el-col>
        <el-col :span="6"><span>试验项目：{{projectForm.cycleTestItemName}}</span></el-col>
        <el-col :span="6" >试验标准：
          <span style="color: #1890ff;cursor:pointer;" @click="downloadA(projectForm.standard.link,projectForm.standard.originalName)">{{ projectForm.cycleTestStandardName }}</span>
          <!-- <a style="color: #1890ff;cursor:pointer;" :href="projectForm.link">{{ projectForm.cycleTestStandardName }} {{projectForm.link}}</a> -->
        </el-col>
      </el-row>
      <el-row :gutter="20" style="padding: 5px 0">
        <el-col :span="6">试验条件：{{ projectForm.cycleTestItemCondition }}</el-col>
        <el-col :span="6">试验件材料：{{ projectForm.testMat }}</el-col>
        <el-col :span="6">最小试验数量：{{ projectForm.minDoTestCount }}</el-col>
        <el-col :span="6">工艺员：{{ projectForm.processUserName }}</el-col>
      </el-row>
      <el-row :gutter="20" style="padding: 5px 0">
        <el-col :span="6">提前下发天数：{{ projectForm.genBefore }}</el-col>
        <el-col :span="6">试验时长：{{ projectForm.testDuration }}</el-col>
        <el-col :span="6">临期提醒天数：{{ projectForm.remind }}</el-col>
        <el-col :span="6">试验周期：
          <span v-if="projectForm.jobType == 1">每周 {{ projectForm.weekList && projectForm.weekList.length }}次</span>
          <span v-if="projectForm.jobType == 2">每月 {{ monthTags && monthTags.length }}次</span>
          <span v-if="projectForm.jobType == 3">每年 {{ yearTags && yearTags.length }}次</span>
          <div style="margin-left: 60px" v-if="projectForm.jobType == 2">
            <el-tag
              v-for="tag in monthTags"
              :key="tag"
              type="info"
              style="width: 86px; margin-right: 5px; margin-top: 10px"
            >
              {{ tag }}
            </el-tag>
          </div>
          <div style="margin-left: 60px" v-if="projectForm.jobType == 1">
            <el-tag
              v-for="tag in projectForm.weekList"
              :key="tag"
              type="info"
              style="width: 86px; margin-right: 5px; margin-top: 10px"
            >
              <span v-if="tag == 1">周一</span>
              <span v-if="tag == 2">周二</span>
              <span v-if="tag == 3">周三</span>
              <span v-if="tag == 4">周四</span>
              <span v-if="tag == 5">周五</span>
              <span v-if="tag == 6">周六</span>
              <span v-if="tag == 7">周日</span>
            </el-tag>
          </div>
          <div style="margin-left: 60px" v-if="projectForm.jobType == 3">
            <el-tag
              v-for="tag in yearTags"
              :key="tag"
              type="info"
              style="width: 86px; margin-right: 5px; margin-top: 10px"
            >
              {{ tag }}
            </el-tag>
          </div>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">维护人：{{ projectForm.updateUserName }}</el-col>
        <el-col :span="6">更新完成时间：{{ projectForm.updateTime }}</el-col>
      </el-row>
    </div>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script>
import { getProjectList,getDetail,getUserList,getPieceList,getPlateList,add,update} from '@/api/qualityManagement/periodicTesting/projectCycle.js';

export default {
  props: {
    showDialog: {
      type: Boolean,
      default: false,
    },
    title:{
        type:String,
        default:''
    },
    row:{
      type:Object,
      default:{}
    }
  },
  data() {
    return {
      openShow: false,
      projectOption:[],
      pieceList:[],
      projectForm: {},
      projectRules: {
        cycleTestItemId: [{ required: true, message: '请输入项目名称', trigger: 'blur' }],
        testType: [{ required: true, message: '请选择试验件', trigger: 'blur' }],
        processUserId: [{ required: true, message: '请选择工艺员', trigger: 'blur' }],
        remind: [{ required: true, message: '请选择超期提醒', trigger: 'blur' }],
        jobType: [{ required: true, message: '请选择试验周期', trigger: 'blur' }],
        testMat:[{required:true,message:'请输入试验件材料',trigger:'blur'}],
        minDoTestCount:[{required:true,message:'请输入最小试验数量',trigger:'blur'}],
      },
      userData:[],
      monthTags:[],
      yearTags:[],
      plateData:[],
    };
  },
  mounted() {
    this.openShow = this.showDialog;
    if(this.row && this.row.id){
      this.getRowDetail(this.row.id)
    }
    this.getPieces()
    this.getUsers()
    this.getProject()
    this.getPlates()
    
    
  },
  methods: {
    downloadStandard(val){

    },
    getRowDetail(id){
      getDetail(id).then(res =>{
        this.projectForm = {
          ...res.data.data,
          isPutOff:res.data.data.isPutOff == 1 ? true : false
        }
        if(this.projectForm.jobType == 1){
          this.projectForm = {
            ...this.projectForm,
            weekList:res.data.data.jobTypeWeekValue.split(','),
          } 
        }else if(this.projectForm.jobType == 2){
          this.monthTags = res.data.data.jobTypeMonthValue.split(',').map(str => {
            const num = parseInt(str, 10); // 转为数字，自动去除前导零
            return num + '日';
          })
        }else if(this.projectForm.jobType == 3){
          this.yearTags = res.data.data.jobTypeYearValue.split(',').map(str => {
            const month = parseInt(str.substring(0, 2), 10); // 取前两位作为月
            const day = parseInt(str.substring(2, 4), 10);   // 取后两位作为日
            return `${month}月${day}日`;
          });
        }
      })
    },
    downloadA(fileUrl, fileName){
      const xhr = new XMLHttpRequest();
      xhr.open('GET', fileUrl, true);
      xhr.responseType = 'blob';
            
      xhr.onload = function () {
        if (xhr.status === 200) {
          const res = xhr.response;
          const link = document.createElement('a');
          link.style.display = 'none';
          const url = window.URL.createObjectURL(res);
          link.href = url;
          link.setAttribute('download', fileName);
          document.body.appendChild(link);
          link.click();
          window.URL.revokeObjectURL(link.href);
          document.body.removeChild(link);
        } else {
          console.error('下载失败:', xhr.status);
          ElMessage.error('下载失败，请稍后重试');
        }
      };
            
      xhr.onerror = function() {
        console.error('下载请求出错');
        ElMessage.error('下载请求出错，请检查网络连接');
      };
            
      xhr.send();
    },
    getPlates(){
      getPlateList().then(res =>{
        this.plateData = res.data.data
      })
    },
    getPieces(){
      getPieceList().then(res =>{
        this.pieceList = res.data.data
      })
    },
    getUsers(){
      getUserList('1993624442365915137').then(res =>{
        this.userData = res.data.data
      })
    },
    closeDialog() {
      this.openShow = false;
      this.$emit('closeDialog');
    },
    getProject(){
        getProjectList().then(res=>{
          this.projectOption = res.data.data
        })
    },
    tpProjectChange(val){
        let selectedOption = this.projectOption.find(option => option.id === val);
        this.projectForm.cycleTestItemCondition = selectedOption.condition
        this.projectForm.cycleTestStandardName = selectedOption.cycleTestStandardName
        
    },  
    // 切换周期
    changeCycle() {
      this.projectForm.monthValue = '';
      this.projectForm.weekList = [];
      this.monthTags = [];
      this.projectForm.yearMonth = '';
      this.projectForm.yearDays = '';
      this.yearTags = [];
    },
    // 添加月份日期
    addMonth() {
      let value = this.projectForm.monthValue + '日';
      if (this.monthTags.find(item => item == value)) return;
      this.monthTags.push(this.projectForm.monthValue + '日')
    },
    // 添加年份日期
    addYears() {
      let value = this.projectForm.yearMonth + '月' + this.projectForm.yearDays + '日';
      if (this.yearTags.find(item => item == value)) return;
      if (this.projectForm.yearMonth == '' || this.projectForm.yearDays == '') return;
      this.yearTags.push(this.projectForm.yearMonth + '月' + this.projectForm.yearDays + '日');
    },
    // 删除月份日期
    closeMonthTag(item, index) {
      this.monthTags = this.monthTags.filter(tags => tags != item);
    },
    // 删除年份日期
    closeYearsTag(item, index) {
      this.yearTags = this.yearTags.filter(tags => tags != item);
    },

    submit(){
        this.$refs.form.validate(valid =>{
          if(valid){
            let monthArr = []
            let yearArr = []
            if(this.projectForm.jobType == 2){
              if(this.monthTags.length == 0){
                this.$message.error('请选择日期')
                return
              }
              monthArr = this.monthTags.map(str => {
                // 提取数字部分（匹配连续的数字）
                const num = str.match(/\d+/)?.[0] || '0';
                // 补零到两位
                return num.padStart(2, '0');
              });
            }
            if(this.projectForm.jobType == 1){
              if(this.projectForm.weekList.length == 0){
                this.$message.error('请选择日期')
                return
              }
            }
            if(this.projectForm.jobType == 3){
              if(this.yearTags.length == 0){
                this.$message.error('请选择日期')
                return
              }
              yearArr =  this.yearTags.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 = {
              testType:this.projectForm.testType,
              plateId:this.projectForm.plateId,
              cycleTestItemId:this.projectForm.cycleTestItemId,
              cycleTestItemCondition:this.projectForm.cycleTestItemCondition,
              cycleTestItemStandard:this.projectForm.cycleTestItemStandard,
              processUserId:this.projectForm.processUserId ? this.projectForm.processUserId : '',
              testDuration:this.projectForm.testDuration ? this.projectForm.testDuration : '',
              genBefore:this.projectForm.genBefore ? this.projectForm.genBefore : '',
              remind:this.projectForm.remind,
              jobType:this.projectForm.jobType,
              jobTypeWeekValue:this.projectForm.jobType == 1 ? this.projectForm.weekList.join(',') : '',
              jobTypeMonthValue:this.projectForm.jobType == 2 ? monthArr.join(',') : '',
              jobTypeYearValue:this.projectForm.jobType == 3 ? yearArr.join(',') : '',
              isPutOff:this.projectForm.isPutOff ? 1 : 0,
              minDoTestCount:this.projectForm.minDoTestCount,
              testMat:this.projectForm.testMat,
            }
            
            console.log('params==============',params)
            console.log('title--------------',this.title)
            if(this.title == '新增'){
              add(params).then(res =>{
                if(res.data.code == 200){
                    this.$message.success('新增成功')
                  this.closeDialog()
                }
              })
            }else{
              params.id = this.projectForm.id
              update(params).then(res =>{
                if(res.data.code == 200){
                    this.$message.success('编辑成功')
                  this.closeDialog()
                }
              })
            }
            
          }
        })
       
    },
  },
};
</script>
<style lang="scss" scoped></style>
