<template>
    <el-dialog title="新增" append-to-body :modelValue="openShow" width="70%" @close="closeDialog">
        <el-form ref="form" :model="form" label-width="150px" :rules="rules">
            <el-row :gutter="24">
                <el-col :span="8">
                    <el-form-item label="作业中心：" prop="workCenterId">
                        <el-select v-model="form.workCenterId" :disabled="type == 'view'" placeholder="请选择" @change="changeWorkCenter">
                            <el-option v-for="item in workList" :key="item.id" :label="item.wcName" :value="item.id" />
                            <!-- <el-option label="作业中心2" value="2" /> -->
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="作业槽：" prop="workTankId">
                        <el-select v-model="form.workTankId" :disabled="type == 'view'" placeholder="请选择">
                            <el-option v-for="item in tankList" :key="item.id" :label="item.workTankCode" :value="item.id" />
                            <!-- <el-option label="作业槽2" value="2" /> -->
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="分析项目：" prop="testElement">
                        <el-input v-model="form.testElement" :disabled="type == 'view'" placeholder="请输入" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <!-- <el-form-item label="工艺含量:" prop="gongyihanliang">
                        <el-input v-model="input" placeholder="请输入" />
                    </el-form-item> -->
                    <el-form-item label="规范上下限(g/L)：" prop="standardLimit">
                        <div style="display: flex;">
                            <el-input v-model="form.normValueMin" :disabled="type == 'view'" placeholder="请输入" />
                            ~<el-input v-model="form.normValueMax" :disabled="type == 'view'" placeholder="请输入" />
                        </div>

                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="目标上下限：">
                        <div style="display: flex;">
                            <el-input v-model="form.targetValueMin" :disabled="type == 'view'" placeholder="请输入" />
                            ~<el-input v-model="form.targetValueMax" :disabled="type == 'view'" placeholder="请输入" />
                        </div>

                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="目标值：" prop="targetValue">
                        <el-input v-model="form.targetValue" :disabled="type == 'view'" placeholder="请输入" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="添加点：">
                        <el-input v-model="form.fillingLocation" :disabled="type == 'view'" placeholder="请输入" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="体积：">
                        <el-input v-model="form.volume" :disabled="type == 'view'" placeholder="请输入" />
                    </el-form-item>
                </el-col>
                 <el-col :span="8">
                    <el-form-item label="测量值单位：" prop="testUnit">
                        <el-input v-model="form.testUnit" :disabled="type == 'view'" placeholder="请输入" />
                    </el-form-item>
                </el-col>
                 <el-col :span="8">
                    <el-form-item label="添加值单位：" prop="addUnit">
                        <el-input v-model="form.addUnit" :disabled="type == 'view'" placeholder="请输入" />
                    </el-form-item>
                </el-col>


                <el-col :span="8">
                    <el-form-item label="加药量计算公式：" prop="addDrugFormulaId" label-width="150px">
                        <el-select v-model="form.addDrugFormulaId" :disabled="type == 'view'" placeholder="请选择">
                            <el-option v-for="item in drugList" :key="item.id" :label="item.name" :value="item.id" />
                            <!-- <el-option label="计算公式2" value="2" /> -->
                        </el-select>
                    </el-form-item>
                </el-col>
                   <el-col :span="8">
                    <el-form-item label="添加后理论值公式：" prop="afterTheoryFormulaId" label-width="150px">
                        <el-select v-model="form.afterTheoryFormulaId" :disabled="type == 'view'" placeholder="请选择">
                            <el-option v-for="item in afterTheoryList" :key="item.id" :label="item.name" :value="item.id" />
                            <!-- <el-option label="计算公式2" value="2" /> -->
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="温度范围：">
                        <div style="display: flex;">
                            <el-radio-group v-model="form.temperatureType" :disabled="type == 'view'">
                                <el-radio :value="1">无温度</el-radio>
                                <el-radio :value="2">室内温度</el-radio>
                                <el-radio :value="3">环境温度</el-radio>
                                <el-radio :value="4">温度范围</el-radio>
                            </el-radio-group>
                        </div>
                        <div style="margin-left: 32px;display: flex;" v-if="form.temperatureType == 2">
                            <el-input v-model="form.temperatureInRoom" :disabled="type == 'view'" placeholder="请输入" />
                        </div>
                        <div style="margin-left: 32px;display: flex;" v-if="form.temperatureType == 3">
                            <el-input v-model="form.temperatureEnv" :disabled="type == 'view'" placeholder="请输入" />
                        </div>
                        <div style="margin-left: 32px;display: flex;" v-if="form.temperatureType == 4">
                            <el-input v-model="form.temperatureRangeLeft" :disabled="type == 'view'" placeholder="请输入" />
                            ~<el-input v-model="form.temperatureRangeRight" :disabled="type == 'view'" placeholder="请输入" />
                        </div>




                    </el-form-item>
                </el-col>
                <el-col :span="24">
                    <el-form-item label="PH值范围：">
                        <div style="display: flex;">
                            <el-radio-group v-model="form.phType" :disabled="type == 'view'">
                                <el-radio :value="1">无PH值</el-radio>
                                <el-radio :value="2">PH值范围</el-radio>
                            </el-radio-group>
                            <div style="margin-left: 32px;display: flex;" v-if="form.phType == 2">
                                <el-input v-model="form.phRangeLeft" :disabled="type == 'view'"  placeholder="请输入" />
                                ~<el-input v-model="form.phRangeRight" :disabled="type == 'view'"  placeholder="请输入" />
                            </div>
                        </div>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="药品名称：">
                        <el-input v-model="form.drugName" :disabled="type == 'view'"  placeholder="请输入" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="药品物料号："  prop="drugMaterialId">
                        <el-select v-model="form.drugMaterialId" :disabled="type == 'view'"  placeholder="请选择" @change="changeGoods">
                            <el-option v-for="item in drugMaterialOptions" :key="item.id" :label="item.goodsCode" :value="item.id" />
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="药品物料名称："  prop="drugMaterialName">
                        <el-input v-model="form.drugMaterialName"  placeholder="请输入" disabled />
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="测试周期(天)：" prop="analysisCycle" >
                        <el-input-number v-model="form.analysisCycle" :disabled="type == 'view'" :min="1" controls-position="right" @change="handleChange" />
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="化验人：" prop="testUserId">
                        <el-select v-model="form.testUserId" :disabled="type == 'view'" placeholder="请选择">
                            <el-option v-for="item in personList" :key="item.id" :label="item.realName" :value="item.id" />
                            <!-- <el-option label="化验人2" value="2" /> -->
                        </el-select>
                    </el-form-item>
                </el-col>

                <el-col :span="8">
                    <el-form-item label="主管工艺：" prop="processUserId">
                        <el-select v-model="form.processUserId" :disabled="type == 'view'" placeholder="请选择">
                            <el-option v-for="item in managerList" :key="item.id" :label="item.realName" :value="item.id" />
                            <!-- <el-option label="工艺2" value="2" /> -->
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="班组：" prop="teamId">
                        <el-select v-model="form.teamId" :disabled="type == 'view'" placeholder="请选择">
                            <el-option v-for="item in teamList" :key="item.id" :label="item.tsName" :value="item.id" />
                            <!-- <el-option label="班组2" value="2" /> -->
                        </el-select>
                    </el-form-item>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="分析周期：" prop="jobType">
                        <el-select placeholder="请选择试验周期" :disabled="type == 'view'" v-model="form.jobType" @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-if="form.jobType == 1">
                        <el-checkbox-group v-model="form.weekList" :disabled="type == 'view'">
                            <el-checkbox style="margin-right:25px !important;" label="周一" value="1" />
                            <el-checkbox style="margin-right:25px !important;" label="周二" value="2"></el-checkbox>
                            <el-checkbox style="margin-right:25px !important;" label="周三" value="3"></el-checkbox>
                            <el-checkbox style="margin-right:25px !important;" label="周四" value="4"></el-checkbox>
                            <el-checkbox style="margin-right:25px !important;" label="周五" value="5"></el-checkbox>
                            <el-checkbox style="margin-right:25px !important;" label="周六" value="6"></el-checkbox>
                            <el-checkbox style="margin-right:25px !important;" label="周日" value="7"></el-checkbox>
                        </el-checkbox-group>
                    </div>
                    <div style="margin-left: 100px;" v-if="form.jobType == 2">
                        <div style="display: flex;align-items: center;" v-if="type != 'view'">
                            <span>时间：每月</span>
                            <el-select v-model="form.monthValue" :disabled="type == 'view'" style="width: 100px;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 :disabled="type == 'view'" v-model="form.isPutOff" label="任务若遇周末或当月无该日期，顺延至下周一" />
                        </div>
                    </div>
                    <div style="margin-left: 100px;" v-if="form.jobType == 3">
                        <div style="display: flex;align-items: center;">
                            <span>时间</span>
                            <el-select v-model="form.yearMonth" style="width: 60px;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="form.yearDays" style="width: 60px;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 :disabled="type == 'view'" v-model="form.isPutOff" label="任务若遇周末或当月无该日期，顺延至下周一" />
                        </div>
                    </div>
                </el-col>
                <el-col :span="8">
                    <el-form-item label="有效期：" prop="validDate">
                        <el-date-picker :disabled="type == 'view'" v-model="form.validDate" type="date" format="YYYY-MM-DD" value-format="YYYY-MM-DD" placeholder="请选择" style="width: 100%;" />
                    </el-form-item>
                </el-col>


            </el-row>
        </el-form>

        <template #footer>
            <span class="dialog-footer">
                <el-button @click="closeDialog(false)">取 消</el-button>
                <el-button type="primary" v-if="type != 'view'" @click="submit">确 定</el-button>
            </span>
        </template>
    </el-dialog>
</template>
<script>
import {getFormula,getTank,getWorkCenter,getPerson,getManager,getTeam,addInfo,getDetail,editInfo,getSelectMaterial} from '@/api/tankSolutionSystem/info'
export default {
    props: {
        showDialog: {
            type: Boolean,
            default: false
        },
        rowId:{
            type:String,
            default:''
        },
        type:{
            type:String,
            default:'add'
        }
    },
    data() {
        var checkStandard = (rule, value, callback) => {
            if(!this.form.normValueMin || !this.form.normValueMax){
                return callback(new Error('规范上下限不能为空'));
            }
            if(!/^-?\d+(\.\d+)?$/.test(this.form.normValueMin) || !/^-?\d+(\.\d+)?$/.test(this.form.normValueMax)){
                return callback(new Error('请输入数字值'));
            }
            if(Number(this.form.normValueMin) > Number(this.form.normValueMax)){
                callback(new Error('上限需比下限大'));
            }else{
                callback()
            }
        };
        return {
            openShow: false,
            form: {},
            drugMaterialOptions:[],
            rules: {
                workCenterId: [
                    { required: true, message: '请选择作业中心', trigger: 'blur' },
                ],
                workTankId: [
                    { required: true, message: '请选择作业槽', trigger: 'blur' },
                ],
                testElement: [
                    { required: true, message: '请输入分析项目', trigger: 'blur' },
                ],
                standardLimit: [
                    // { required: true, message: '请选择', trigger: 'blur' },
                    {required: true,validator: checkStandard, trigger: 'blur'}
                ],
                targetValue: [
                    { required: true, message: '请输入目标值', trigger: 'blur' },
                ],
                addDrugFormulaId: [
                    { required: true, message: '请选择加药量计算公式', trigger: 'blur' },
                ],
                afterTheoryFormulaId: [
                    { required: true, message: '请选择添加后理论值公式', trigger: 'blur' },
                ],
                testUserId: [
                    { required: true, message: '请选择化验人', trigger: 'blur' },
                ],
                processUserId: [
                    { required: true, message: '请选择主管工艺', trigger: 'blur' },
                ],
                validDate: [
                    { required: true, message: '请选择有效期', trigger: 'blur' },
                ],
                analysisCycle: [
                    { required: true, message: '请选择测试周期', trigger: 'blur' },
                ],
                jobType: [
                    { required: true, message: '请选择分析周期', trigger: 'blur' },
                ],
                // drugMaterialId: [
                //     { required: true, message: '请选择', trigger: 'blur' },
                // ],
                // drugMaterialName: [
                //     { required: true, message: '请输入', trigger: 'blur' },
                // ],
                teamId: [
                    { required: true, message: '请选择班组', trigger: 'blur' },
                ],
                testUnit:[
                    { required: true, message: '请输入测量值单位', trigger: 'blur' },
                ],
                addUnit:[
                    { required: true, message: '请输入添加值单位', trigger: 'blur' },
                ],
            },
            workList:[],
            monthTags: [],
            yearTags: [],
            drugList:[],
            afterTheoryList:[],
            tankList:[],
            personList:[],
            managerList:[],
            teamList:[]
        }
    },
    mounted() {
        this.openShow = this.showDialog
        this.getFormulaList()
        this.getWorkCenterList()
        this.getTankList()
        this.getPersonList()
        this.getManagerList()
        this.getTeamList()
        this.getGoods()
        if(this.rowId){
            this.getInfoDetail()
        }
    },
    methods: {
        getGoods(){
            getSelectMaterial().then(res =>{
                this.drugMaterialOptions = res.data.data
            })
        },
        changeGoods(val){
            let tmp = this.drugMaterialOptions.find(item => item.id == val)
            this.form.drugMaterialName = tmp.goodsName
        },
        // 获取详情
        getInfoDetail(){
            getDetail({id:this.rowId}).then(res =>{
                this.form = {
                    ...res.data.data,
                    isPutOff:res.data.data.isPutOff == 1 ? true : false,
                    teamId:res.data.data.teamId + '',
                    drugMaterialId:res.data.data.drugMaterialId + '',
                    workCenterId:res.data.data.workCenterId + '',
                    testUserId:res.data.data.testUserId + '',
                }
                if(this.form.jobType == 1){
                    this.form = {
                        ...this.form,
                        weekList:res.data.data.jobTypeWeekValue.split(','),
                    } 
                }else if(this.form.jobType == 2){
                    this.monthTags = res.data.data.jobTypeMonthValue.split(',').map(str => {
                        const num = parseInt(str, 10); // 转为数字，自动去除前导零
                        return num + '日';
                    })
                }else if(this.form.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}日`;
                    });
                }
            })
        },
        // 作业中心下拉
        getWorkCenterList(){
            getWorkCenter().then(res =>{
                this.workList = res.data.data
            })
        },
        // 主管工艺下拉
        getManagerList(){
            getManager().then(res =>{
                this.managerList = res.data.data
            })
        },
        // 班组下拉
        getTeamList(){
            getTeam().then(res =>{
                this.teamList = res.data.data
            })
        },
        // 获取添加量计算公式
        getFormulaList(){
            getFormula({formulaType:1}).then(res =>{
                this.drugList = res.data.data
            })
            getFormula({formulaType:2}).then(res =>{
                this.afterTheoryList = res.data.data
            })
        },
        // 查询作业槽下拉列表
        getTankList(val){
            getTank({workstationId:val ? val : ''}).then(res =>{
                this.tankList = res.data.data
            })
        },
        // 化验人下拉
        getPersonList(){
            getPerson().then(res =>{
                res.data.data.map(item =>{
                    item.id = item.id + ''
                })
                this.personList = res.data.data
            })
        },
        // 切换作业中心
        changeWorkCenter(){
            this.form.workTankId = ''
            this.getTankList(this.form.workCenterId)
        },
        // 切换周期
        changeCycle() {
            this.form.monthValue = ''
            this.form.weekList = []
            this.monthTags = []
            this.form.yearMonth = ''
            this.form.yearDays = ''
            this.yearTags = []
        },
        // 添加月份日期
        addMonth() {
            if(this.type == 'view'){
                return
            }
            if(!this.form.monthValue) return
            let value = this.form.monthValue + '日'
            if (this.monthTags.find(item => item == value)) return
            this.monthTags.push(this.form.monthValue + '日')
        },
        // 添加年份日期
        addYears() {
            let value = this.form.yearMonth + '月' + this.form.yearDays + '日'
            if (this.yearTags.find(item => item == value)) return
            if (this.form.yearMonth == '' || this.form.yearDays == '') return
            this.yearTags.push(this.form.yearMonth + '月' + this.form.yearDays + '日')
        },
        // 删除月份日期
        closeMonthTag(item, index) {
            if(this.type == 'view'){
                return
            }
            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){
                    console.log('form---------------',this.form)
                    let monthArr = []
                    let yearArr = []
                    if(this.form.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.form.jobType == 1){
                        if(this.form.weekList.length == 0){
                            this.$message.error('请选择日期')
                            return
                        }
                    }
                    if(this.form.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 = {
                        workCenterId:this.form.workCenterId,
                        workTankId:this.form.workTankId,
                        testElement:this.form.testElement,
                        normValueMin:this.form.normValueMin,
                        normValueMax:this.form.normValueMax,
                        targetValueMin:this.form.targetValueMin ? this.form.targetValueMin : '',
                        targetValueMax:this.form.targetValueMax ? this.form.targetValueMax : '',
                        targetValue:this.form.targetValue,
                        fillingLocation:this.form.fillingLocation ? this.form.fillingLocation : '',
                        volume:this.form.volume ? this.form.volume : '',
                        testUnit:this.form.testUnit,
                        addUnit:this.form.addUnit,
                        addDrugFormulaId:this.form.addDrugFormulaId,
                        afterTheoryFormulaId:this.form.afterTheoryFormulaId,
                        temperatureType:this.form.temperatureType ? this.form.temperatureType : '',
                        temperatureInRoom:this.form.temperatureInRoom ? this.form.temperatureInRoom : '',
                        temperatureEnv:this.form.temperatureEnv ? this.form.temperatureEnv : '',
                        temperatureRangeLeft:this.form.temperatureRangeLeft ? this.form.temperatureRangeLeft : '',
                        temperatureRangeRight:this.form.temperatureRangeRight ? this.form.temperatureRangeRight : '',
                        phType:this.form.phType ? this.form.phType : '',
                        phRangeLeft:this.form.phRangeLeft ? this.form.phRangeLeft : '',
                        phRangeRight:this.form.phRangeRight ? this.form.phRangeRight : '',
                        drugName:this.form.drugName ? this.form.drugName : '',
                        drugMaterialId:this.form.drugMaterialId ? this.form.drugMaterialId : '',
                        drugMaterialName:this.form.drugMaterialName ? this.form.drugMaterialName : '',
                        testUserId:this.form.testUserId,
                        processUserId:this.form.processUserId,
                        teamId:this.form.teamId,
                        jobType:this.form.jobType,
                        jobTypeWeekValue:this.form.jobType == 1 ? this.form.weekList.join(',') : '',
                        jobTypeMonthValue:this.form.jobType == 2 ? monthArr.join(',') : '',
                        jobTypeYearValue:this.form.jobType == 3 ? yearArr.join(',') : '',
                        isPutOff:this.form.isPutOff ? 1 : 0,
                        validDate:this.form.validDate,
                        analysisCycle:this.form.analysisCycle
                    }
                    console.log('params----------------',params)
                    if(this.type == 'add'){
                       addInfo(params).then(res =>{
                            if(res.data.code == 200){
                                this.$message.success('新增成功')
                                this.closeDialog(true)
                            }
                        }) 
                    }else{
                        editInfo({...params,id:this.rowId}).then(res =>{
                            if(res.data.code == 200){
                                this.$message.success('修改成功')
                                this.closeDialog(true)
                            }
                        })
                    }
                    
                }
            })
        },
        closeDialog(val) {
            this.openShow = false
            this.$emit('closeDialog',val);
        }
    }
}
</script>
<style lang="scss" scoped></style>