<template>
    <div class="sampleTemplateDetails">
        <el-row class="taflow-ps-top">
            <i class="el-icon-back" @click="backJumpMethods()"></i>
            <span>样品模板详情</span>
        </el-row>
        <el-row class="taflow-main">
            <DoorView class="moduleRecord" title="样品基础信息">
                <div slot="main" class="taflow-door-box">
                    <el-form :inline="true" ref="form" :model="newObject" class="demo-form-inline" :rules="rules" label-position="top">
                        <el-form-item label="所属分厂" prop="branchName">
                            <el-input v-model="newObject.branchName" placeholder="请输入" maxlength="64" style="width:300px"></el-input>
                        </el-form-item>
                        <el-form-item label="样品分类" prop="sampleType">
                            <el-input v-model="newObject.sampleType" placeholder="请输入" maxlength="64" style="width:300px"></el-input>
                        </el-form-item>
                        <el-form-item label="样品名称" prop="sampleName">
                            <el-input v-model="newObject.sampleName" placeholder="请输入" maxlength="64" style="width:300px"></el-input>
                        </el-form-item>
                        <el-form-item label="审核人" prop="reviewer">
                            <el-select v-model="newObject.reviewer" placeholder="请选择" style="width:300px">
                                <el-option v-for="(item,index) in reviewerList" :key="index" :label="item.nickName" :value="item.userName"></el-option>
                            </el-select>
                        </el-form-item>
                    </el-form>
                </div>
            </DoorView>
            <!-- 编辑状态  $route.query.type == 1  else 新建状态-->
            <div v-if="$route.query.status == 1">
                <SamplesCom ref="samplesCom" :tableData="newObject.sampleAddressList" :hongxin="getSampleTemplateInfoDetail" class="moduleRecord" />
                <SampleCustomInformationCom ref="sampleCustomInformationCom" :tableData="newObject.sampleCustomizeInfoList" :hongxin="getSampleTemplateInfoDetail" class="moduleRecord" />
                <CheckItemsCom ref="checkItemsCom" :tableData="newObject.sampleInspectionItemVOList" :hongxin="getSampleTemplateInfoDetail" class="moduleRecord" />
            </div>
            <div v-else>
                <SamplesCom ref="samplesCom" class="moduleRecord" />
                <SampleCustomInformationCom ref="sampleCustomInformationCom" class="moduleRecord" />
                <CheckItemsCom ref="checkItemsCom" class="moduleRecord" />
            </div>
            <DoorView title="检验结果通知方">
                <div slot="main">
                    <!-- <el-tree ref="tree" :default-expand-all="true" :data="newObject.listTreeSelectVO" show-checkbox node-key="id" :default-checked-keys="dfEhecked" :props="defaultProps">
          </el-tree>-->
                    <el-cascader style="min-width: 310px;" v-model="receiver" :options="newObject.listTreeSelectVO" :props="{ multiple: true, value: 'id', checkStrictly: true }" clearable></el-cascader>
                </div>
            </DoorView>
        </el-row>
        <TabBar>
            <el-row slot="tabBar-Right">
                <el-button size="small" @click="backJumpMethods">返回</el-button>
                <el-button size="small" type="primary" @click="saveDraftsClick">保存</el-button>
            </el-row>
        </TabBar>
    </div>
</template>

<script>
import DoorView from "@/components/YuComponents/DoorView.vue";
import SamplesCom from "./SamplesCom";
import SampleCustomInformationCom from "./SampleCustomInformationCom";
import CheckItemsCom from "./CheckItemsCom";
import TabBar from "@/components/MingComponents/TabBar.vue";
export default {
    name: "sampleTemplateDetails",
    data() {
        return {
            headerData: this.$route.query,
            receiver: [], //通知方
            //备份内容
            backup: [],
            loading: false,
            form: {},
            rules: {
                branchName: [{
                    required: true,
                    message: "请输入所属分厂",
                    trigger: "change",
                }, ],
                sampleType: [{
                    required: true,
                    message: "请输入样品分类",
                    trigger: "change",
                }, ],
                sampleName: [{
                    required: true,
                    message: "请输入样品名称",
                    trigger: "change",
                }, ],
                reviewer: [{
                    required: true,
                    message: "请输入审核人",
                    trigger: "change",
                }, ],
            },
            // defaultProps: {
            //     children: 'children',
            //     label: 'label'
            // },
            //新增对象
            newObject: {
                //样品基础信息
                branchName: "",
                sampleType: "",
                sampleName: "",
                reviewer: "",
                deptIds: "", //通知部门id
                //样品取样地点列表
                sampleAddressList: [],
                //样品自定义信息
                sampleCustomizeInfoList: [],
                //检验项列表
                sampleInspectionItemVOList: [],
                listTreeSelectVO: [], //工作树列表
            },
            reviewerList: [], //审核人列表
        };
    },
    components: {
        DoorView,
        SamplesCom,
        SampleCustomInformationCom,
        CheckItemsCom,
        TabBar,
    },
    created() {},
    computed: {},
    methods: {
        backJumpMethods() {
            this.$router.push({
                path: "sampleTemplateManagement",
            });
        },
        //样品模板详情保存
        async saveSampleTemplateInfoDetail(query) {
            query.id = this.$route.query.id || null;
            const res = await this.$api.sampleTemplateManagement
                .saveSampleTemplateInfoDetail(query)
                .then((response) => {
                    if (response.code === 200) {
                        this.backJumpMethods();
                    }
                });
        },
        saveDraftsClick() {
            let valid1 = false; //基础信息校验
            let valid2 = false; //样品自定义校验
            let valid3 = false; //样品取样地点校验
            //基础信息
            this.$refs["form"].validate((valid) => {
                valid1 = valid;
            });
            if (!valid1) return;

            //样品取样地点
            if (
                !this.$refs.samplesCom.model.newTableData ||
                !this.$refs.samplesCom.model.newTableData.length
            ) {
                this.$message.warning("请添加样品取样地点");
                return;
            }
            this.$refs.samplesCom.$refs.form.validate((valid) => {
                valid3 = valid;
                let addressvalid = false;
                this.$refs.samplesCom.model.newTableData.forEach((element) => {
                    if (!element.address) {
                        addressvalid = true;
                    }
                });
                if (addressvalid) {
                    this.$message.warning("取样地点不能为空");
                    return;
                }
            });
            if (!valid3) return;
            this.newObject.sampleAddressList = this.$refs.samplesCom.model.newTableData;

            //样品取样地点
            if (
                this.$refs.sampleCustomInformationCom.model.newTableData &&
                this.$refs.sampleCustomInformationCom.model.newTableData.length
            ) {
                console.log(this.$refs.sampleCustomInformationCom.$refs.form);
                this.$refs.sampleCustomInformationCom.$refs.form.validate((valid) => {
                    valid2 = valid;
                    let valid2fieldName = false;
                    let valid2valueAttributes = false;
                    this.$refs.sampleCustomInformationCom.model.newTableData.forEach(
                        (element) => {
                            if (!element.fieldName) {
                                valid2fieldName = true;
                            }
                            if (
                                !element.valueAttributes &&
                                element.valueAttributes !== 0 &&
                                element.fieldType != 4
                            ) {
                                valid2 = false;
                                valid2valueAttributes = true;
                            }
                        }
                    );
                    if (valid2fieldName) {
                        this.$message.warning("自定义信息字段名称不能为空");
                        return;
                    }
                    if (valid2valueAttributes) {
                        this.$message.warning("自定义信息输入属性不能为空");
                        return;
                    }
                });
            } else {
                valid2 = true;
            }
            if (!valid2) return;
            this.newObject.sampleCustomizeInfoList = this.$refs.sampleCustomInformationCom.model.newTableData;

            if (
                !this.$refs.checkItemsCom.newTableData ||
                !this.$refs.checkItemsCom.newTableData.length
            ) {
                this.$message.warning("请添加检验项数据");
                return;
            }
            this.newObject.sampleInspectionItemVOList = this.$refs.checkItemsCom.newTableData;
            // this.newObject.deptIds = this.$refs.tree.getCheckedKeys().toString() //获取当前选中部门id
            let arr = [];
            this.receiver.forEach((item) => {
                arr.push(item[item.length - 1]);
            });
            this.newObject.deptIds = arr.toString();
            console.log(this.newObject.deptIds);
            if (valid1 && valid2 && valid3) {
                delete this.newObject.listTreeSelectVO;
                this.saveSampleTemplateInfoDetail(this.newObject);
            }
        },
        //审核人下拉列表
        async getSampleTemplateInfoDetailUsers() {
            const res = await this.$api.sampleTemplateManagement
                .getSampleTemplateInfoDetailUsers()
                .then((response) => {
                    if (response.code === 200) {
                        this.reviewerList = response.data;
                    }
                });
        },
        //查看编辑详情
        async getSampleTemplateInfoDetail({
            id = null
        } = this.$route.query) {
            if (id) {
                const res = await this.$api.sampleTemplateManagement
                    .getSampleTemplateInfoDetail(id)
                    .then((response) => {
                        if (response.code === 200) {
                            this.newObject = response.data;
                            this.newObject.sampleCustomizeInfoList = this.newObject.sampleCustomizeInfoList.map(
                                (item) => {
                                    switch (item.fieldType) {
                                        case 1:
                                            item.fieldTextName = "文本";
                                            break;
                                        case 2:
                                            item.fieldTextName = "选项";
                                            break;
                                        case 3:
                                            item.fieldTextName = "数值";
                                            break;
                                        case 4:
                                            item.fieldTextName = "日期";
                                            break;
                                    }
                                    return item;
                                }
                            );
                            this.newObject.sampleCustomizeInfoList = this.newObject.sampleCustomizeInfoList.map(
                                (item) => {
                                    item.edit = false;
                                    return item;
                                }
                            );
                            this.newObject.sampleAddressList = this.newObject.sampleAddressList.map(
                                (item) => {
                                    item.edit = false;
                                    return item;
                                }
                            );
                            this.foreachChildren(this.newObject.listTreeSelectVO);
                            console.log(this.receiver, '0097');
                            let arr = this.receiver;
                            this.receiver = []
                            this.foreachChild2(arr)
                            console.log(this.receiver,'876');
                        }
                    });
            } else {
                this.listDepts();
            }
        },
        //递归判断默认勾选项
        foreachChildren(dataArr, keyArr = []) {
            // console.log(dataArr);
            for (let i = 0; i < dataArr.length; i++) {
                let arr = dataArr[i];
                // let karr = [...keyArr];
                // karr.push(arr.id);
                if (arr.hasOwnProperty("children")) {
                    this.foreachChildren(arr.children);
                } 
                if (arr.isChoosed) {
                    // this.receiver = this.dfExpanded.concat(karr);
                    this.receiver.push(arr.id);

                    // this.dfEhecked = this.dfEhecked.concat([karr[karr.length - 1]]);
                }
            }
        },
        foreachChild2(arr) {
            this.newObject.listTreeSelectVO.forEach(parent => {
                if (arr.includes(parent.id)) {
                    this.receiver.push([parent.id])
                }
                if (parent.children) {
                    parent.children.forEach(child => {
                        if (arr.includes(child.id)) {
                            this.receiver.push([parent.id, child.id])
                        }
                        if (child.children) {
                            child.children.forEach(item => {
                                if (arr.includes(item.id)) {
                                    this.receiver.push([parent.id, child.id, item.id])
                                }
                            })
                        }
                    })
                }

            })
        },
        // foreachChild(dataArr) {
        //   this.newObject.listTreeSelectVO.forEach((parent) => {
        //     if (dataArr.includes(String(parent.id))) {
        //       this.receiver.push([parent.id]);
        //     }
        //   });
        //   for (let i = 0; i < this.newObject.receiver.length; i++) {
        //     let item = this.newObject.receiver[i];
        //     console.log(this.foreachChildren2(item.id, this.receiver, []));
        //   }
        //   // value.forEach(parent => {
        //   //     if (res.data.particulars.includes(String(parent.id))) {
        //   //         this.basisViewForm.receiver.push([parent.id])
        //   //     }
        //   //     parent.children.forEach(child => {
        //   //         if (res.data.particulars.includes(String(child.id))) {
        //   //             this.basisViewForm.receiver.push([parent.id, child.id])
        //   //         }
        //   //         child.children.forEach(item => {
        //   //             if (res.data.particulars.includes(String(item.id))) {
        //   //                 this.basisViewForm.receiver.push([parent.id, child.id, item.id])
        //   //             }
        //   //         })
        //   //     })
        //   // })
        // },
        // foreachChild2(id, arr, save = "") {
        //   let sa = save;
        //   for (let i = 0; i < arr.length; i++) {
        //     if (arr[i].includes(String(id))) {
        //       sa.push(arr[i].id);
        //       return sa;
        //     } else if (
        //       !arr[i].includes(String(id)) &&
        //       !arr[i].hasOwnProperty("children")
        //     ) {
        //       sa.push(id);
        //       return sa;
        //     } else {
        //       sa.push(id);
        //       return foreachChildren2(id, arr[i], sa);
        //     }
        //   }
        // },
        //查询工作树列表
        async listDepts() {
            const res = await this.$api.sampleTemplateManagement
                .listDepts()
                .then((response) => {
                    if (response.code === 200) {
                        this.newObject.listTreeSelectVO = response.data || [];
                        // this.foreachChildren(this.newObject.listTreeSelectVO);
                    }
                });
        },
    },
    created() {
        this.getSampleTemplateInfoDetailUsers();
        this.getSampleTemplateInfoDetail();
    },
    mounted() {},
};
</script>

<style lang="scss">
.sampleTemplateDetails {
    background-color: #ecf0f3;
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;

    .el-link {
        margin-right: 16px;
    }

    .taflow-main {
        flex: 1;
        overflow-y: auto;

        .moduleRecord {
            margin: 16px;
        }

        .taflow-door-box {
            &>div {
                &:nth-child(n + 2) {
                    margin-top: 24px;
                }

                div:first-child {
                    margin-bottom: 8px;
                }
            }

            .el-form-item {
                //   margin-right:18%;
                width: calc((100% - 24px) / 3);
                margin-right: 0;
            }

            .el-form-item-esle {
                //   margin-right:18%;
                width: auto;
                margin-right: 0;

                .el-form-item {
                    //   margin-right:18%;
                    max-width: 150px;
                    margin-right: 0;

                    input {
                        width: 100%;
                    }
                }
            }

            .fiw {
                width: 60%;
                min-width: 100px;
            }
        }
    }

    .taflow-ps-top {
        width: auto;
        height: 60px;
        padding: 0 16px;
        position: sticky;
        top: 0;
        left: 0;
        display: flex;
        align-items: center;
        font-size: 20px;
        background: #fff;
        z-index: 20;

        .el-icon-back {
            display: block;
            font-size: 26px;
            margin-right: 8px;
            cursor: pointer;
        }
    }
}
</style>
