<template>
    <div class="app-container" id="newAccessoryAccept">
        <el-form
            :model="maForm"
            ref="maForm"
            :rules="maRules"
            size="small"
            :inline="true"
            label-width="80px"
        >
            <el-form-item label="采购日期" prop="purchaseTime">
                <el-date-picker
                    v-model="maForm.purchaseTime"
                    style="width: 240px"
                    value-format="yyyy-MM-dd"
                    type="date"
                    :disabled="isDisabled"
                    placeholder="请选择采购日期"
                ></el-date-picker>
            </el-form-item>
            <el-form-item label="到货日期" prop="arrivalTime">
                <el-date-picker
                    v-model="maForm.arrivalTime"
                    style="width: 240px"
                    value-format="yyyy-MM-dd"
                    type="date"
                    :disabled="isDisabled"
                    :picker-options="pickerOptions"
                    placeholder="请选择到货日期"
                ></el-date-picker>
            </el-form-item>
            <el-form-item label="采购员" prop="purchaser">
                <el-select
                    v-model="maForm.purchaser"
                    filterable
                    placeholder="请选择采购员"
                    style="width: 240px"
                    :disabled="isDisabled"
                >
                    <el-option
                        v-for="item in userList"
                        :key="item.userId"
                        :label="item.userName"
                        :value="item.userId"
                    ></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="remark">
                <el-input
                    v-model="maForm.remark"
                    placeholder="请输入备注"
                    clearable
                    :disabled="isDisabled"
                    type="textarea"
                    maxlength="150"
                    rows="1"
                    style="width: 240px"
                />
            </el-form-item>
        </el-form>

        <el-form
            :model="addForm"
            ref="addForm"
            size="small"
            :inline="true"
            v-show="showSearch"
            label-width="80px"
        >
            <el-form-item label="配件类型" prop="equipmentId">
                <treeselect
                    v-model="addForm.equipmentId"
                    default-expand-all
                    :options="equipmentTypeList"
                    :disable-branch-nodes="true"
                    placeholder="请选择机具类型"
                    @select="select"
                    :disabled="isDisabled"
                    style="width: 240px"
                />
            </el-form-item>
            <el-form-item label="配件厂家" prop="supplierId">
                <el-select
                    v-model="addForm.supplierId"
                    placeholder="配件厂家"
                    clearable
                    filterable
                    :disabled="isDisabled"
                    style="width: 240px"
                    @change="changeSupplier"
                >
                    <el-option
                        v-for="item in supplierList"
                        :key="item.supplierId"
                        :label="item.supplier"
                        :value="item.supplierId"
                    />
                </el-select>
            </el-form-item>
        </el-form>

        <el-row :gutter="10" class="mb8">
            <!-- <el-col :span="1.5">
                <el-button
                    type="success"
                    plain
                    icon="el-icon-back"
                    size="mini"
                    @click="jumpList"
                    >新购配件管理</el-button
                >
            </el-col> -->
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    v-if="!isDisabled"
                    @click="handleSave"
                    >保存</el-button
                >
            </el-col>
            <el-col :span="1.5">
                <el-button
                    type="primary"
                    plain
                    icon="el-icon-plus"
                    size="mini"
                    v-if="isCheck"
                    :disabled="multiple"
                    @click="handleListCheck"
                    v-hasPermi="['newPurchase:parts:notice:accept:batch']"
                    >批量验收</el-button
                >
            </el-col>
            <!-- <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete" 
        >删除</el-button>
      </el-col>-->
            <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport" 
        >导出</el-button>
      </el-col>-->
        </el-row>

        <el-table
            v-loading="loading"
            :data="equipmentList"
            @selection-change="handleSelectionChange"
        >
            <el-table-column
                type="selection"
                width="55"
                align="center"
                :selectable="selectable"
            />
            <el-table-column
                label="序号"
                align="center"
                width="100"
                type="index"
            />
            <el-table-column
                label="配件名称"
                align="center"
                prop="machineTypeName"
                :show-overflow-tooltip="true"
            />
            <el-table-column
                label="配件规格"
                align="center"
                prop="specificationType"
                :show-overflow-tooltip="true"
            />
            <el-table-column label="计量单位" align="center" prop="unitName" />
            <el-table-column
                label="购置单价（元)"
                align="center"
                prop="purchasePrice"
            >
                <template slot-scope="scope">
                    <el-input-number
                        v-model="scope.row.purchasePrice"
                        controls-position="right"
                        :disabled="isCheck || isView"
                        style="width: 100%"
                        :min="0"
                    ></el-input-number>
                </template>
            </el-table-column>

            <el-table-column label="采购数量" align="center" prop="purchaseNum">
                <template slot-scope="scope">
                    <el-input-number
                        v-model="scope.row.purchaseNum"
                        controls-position="right"
                        :disabled="isCheck || isView"
                        style="width: 100%"
                        :min="1"
                    ></el-input-number>
                </template>
            </el-table-column>

            <el-table-column
                label="厂家"
                align="center"
                prop="supplierId"
                width="200"
            >
                <template slot-scope="scope">
                    <el-select
                        v-model="scope.row.supplierId"
                        filterable
                        placeholder="厂家"
                        clearable
                        style="width: 180px"
                        :disabled="isCheck || isView"
                    >
                        <el-option
                            v-for="item in supplierList"
                            :key="item.supplierId"
                            :label="item.supplier"
                            :value="item.supplierId"
                        />
                    </el-select>
                </template>
            </el-table-column>
            <el-table-column
                label="状态"
                align="center"
                prop="statusResult"
            ></el-table-column>
            <el-table-column
                label="操作"
                align="center"
                class-name="small-padding fixed-width"
                v-if="!isView || isCheck || isEdit"
            >
                <template slot-scope="scope" v-if="scope.row.roleId !== 1">
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-edit"
                        v-if="isCheck && scope.row.status == 0"
                        @click="handleCheck(scope.row)"
                        v-hasPermi="['newPurchase:parts:notice:accept']"
                        >验收</el-button
                    >
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        v-if="!isCheck && scope.row.status == 0"
                        @click="handleDelete(scope.row)"
                        >删除</el-button
                    >
                    <el-button
                        size="mini"
                        type="text"
                        icon="el-icon-delete"
                        v-if="isShow"
                        @click="handleDelete(scope.row)"
                        >删除</el-button
                    >
                </template>
            </el-table-column>
        </el-table>

        <!-- 验收对话框 -->
        <el-dialog
            :title="title"
            :visible.sync="open"
            width="500px"
            append-to-body
            :close-on-click-modal="false"
        >
            <el-form
                ref="form"
                :model="form"
                :rules="rules"
                label-width="120px"
            >
                <el-form-item label="配件名称:" prop="machineTypeName">
                    <el-input
                        v-model="form.machineTypeName"
                        disabled
                        maxlength="50"
                    />
                </el-form-item>
                <el-form-item label="配件型号" prop="specificationType">
                    <el-input
                        v-model="form.specificationType"
                        disabled
                        maxlength="50"
                    />
                </el-form-item>
                <el-form-item label="验收数量" prop="purchaseNum">
                    <el-input
                        v-model="form.purchaseNum"
                        disabled
                        maxlength="50"
                    />
                </el-form-item>
                <el-form-item label="验收结论" prop="checkResult">
                    <el-radio v-model="form.checkResult" label="通过"
                        >通过</el-radio
                    >
                    <el-radio v-model="form.checkResult" label="不通过"
                        >不通过</el-radio
                    >
                </el-form-item>
                <el-form-item label="验收通过数量" prop="checkNum">
                    <el-input-number
                        v-model="form.checkNum"
                        style="width: 100%"
                        controls-position="right"
                        :min="1"
                        :max="form.purchaseNum"
                    />
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="submitForm">确 定</el-button>
                <el-button @click="cancel">取 消</el-button>
            </div>
        </el-dialog>

        <!-- 批量验收弹窗 -->
        <el-dialog
            :title="title"
            :visible.sync="openAll"
            width="650px"
            append-to-body
        >
            <el-form
                ref="aform"
                :model="aform"
                :rules="arules"
                label-width="120px"
            >
                <el-form-item label="验收结论" prop="checkResult">
                    <el-radio v-model="aform.checkResult" label="通过"
                        >通过</el-radio
                    >
                    <el-radio v-model="aform.checkResult" label="不通过"
                        >不通过</el-radio
                    >
                </el-form-item>
                <!-- <el-form-item label="验收图片" prop="checkUrl">
          <el-upload 
                :http-request="(obj) => imgUpLoad(obj,'fileUrl')"
                action="#" 
                :file-list="fileList"
                :show-file-list="false"
                list-type="picture-card"
                accept=".png,.jpg,.jpeg"
                :on-success="handleAvatarSuccess"
                :on-preview="handlePictureCardPreview"
                :on-remove="handleRemove">
                <img v-if="imageUrl" :src="uploadUrl+imageUrl" style="width: 140px;height: 140px;" class="avatar">
                <i v-else class="el-icon-plus avatar-uploader-icon"></i>
              </el-upload>
        </el-form-item>-->
            </el-form>
            <div slot="footer" class="dialog-footer" style="text-align: center">
                <el-button type="primary" @click="submitListForm"
                    >确 定</el-button
                >
                <el-button @click="openAll = false">取 消</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { equipmentTypeTree, supplierInfoList } from '@/api/store/tools'
import { getUserByRoleList } from '@/api/system/user'
import {
    getAccessoryTree,
    addPurchaseAccessory,
    getPurchaseAccessoryDetails,
    updatePurchaseAccessory,
    checkPurchaseAccessory,
} from '@/api/store/newBuy'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
export default {
    name: 'NewAccessoryAccept',
    dicts: ['sys_normal_disable'],
    components: { Treeselect },
    props: {
        isView: {
            type: Boolean,
            default: () => {
                return false
            },
        },
        isEdit: {
            type: Boolean,
            default: () => {
                return false
            },
        },
        isCheck: {
            type: Boolean,
            default: () => {
                return false
            },
        },
        isDisabled: {
            type: Boolean,
            default: () => {
                return false
            },
        },
        isShow: {
            type: Boolean,
            default: () => {
                return false
            },
        },
        partsTaskId: {
            type: [String, Number],
        },
    },
    data() {
        return {
            // 遮罩层
            loading: false,
            // 选中数组
            ids: [],
            // 非单个禁用
            single: true,
            // 非多个禁用
            multiple: true,
            // 显示搜索条件
            showSearch: true,
            // 总条数
            total: 0,
            // 表格数据
            equipmentList: [],
            // 弹出层标题
            title: '',
            // 是否显示弹出层
            open: false,
            // 是否显示弹出层（数据权限）
            menuExpand: false,
            menuNodeAll: false,
            deptExpand: true,
            deptNodeAll: false,
            // 日期范围
            dateRange: [],
            userList: [],
            supplierList: [],
            equipmentTypeList: [],
            // 表单参数
            form: {},
            defaultProps: {
                children: 'children',
                label: 'label',
            },
            taskId: '',
            // isView: false,
            // isShow: false,
            // isEdit: false,
            // isCheck: false,
            addForm: {
                equipmentId: undefined,
                supplierId: '',
            },
            maForm: {
                purchaseTime: '',
                arrivalTime: '',
                purchaser: '',
                remark: '',
            },
            openAll: false,
            // 表单参数
            aform: {},
            // 表单校验
            arules: {
                checkResult: [
                    {
                        required: true,
                        message: '验收结论不能为空',
                        trigger: 'blur',
                    },
                ],
                checkUrl: [
                    {
                        required: true,
                        message: '验收图片不能为空',
                        trigger: 'blur',
                    },
                ],
            },

            rules: {
                checkResult: [
                    {
                        required: true,
                        message: '验收结论不能为空',
                        trigger: 'blur',
                    },
                ],
                checkNum: [
                    {
                        required: true,
                        message: '验收通过数量不能为空',
                        trigger: 'blur',
                    },
                ],
            },
            // 表单校验
            maRules: {
                purchaseTime: [
                    {
                        required: true,
                        message: '采购日期不能为空',
                        trigger: 'blur',
                    },
                ],
                arrivalTime: [
                    {
                        required: true,
                        message: '到货日期不能为空',
                        trigger: 'blur',
                    },
                ],
                // purchaser: [
                //   { required: true, message: "采购员不能为空", trigger: "blur" }
                // ]
            },
        }
    },
    computed: {
        pickerOptions() {
            return {
                disabledDate(time) {
                    const currentDate = new Date()
                    currentDate.setHours(0, 0, 0, 0)
                    return time.getTime() < currentDate.getTime()
                },
            }
        },
    },
    watch: {
        'maForm.purchaseTime'() {
            if (this.maForm.purchaseTime != '') {
                this.maForm.arrivalTime = ''
            }
        },
    },
    created() {
        // const isShow = this.$route.query && this.$route.query.isShow
        // if (isShow && isShow == 'true') {
        //     this.isShow = true
        // } else {
        //     this.isShow = false
        // }
        // const taskId = this.$route.query && this.$route.query.taskId
        // this.taskId = taskId
        // if (this.taskId == '' || !this.taskId) {
        //     this.isEdit = false
        // } else if (this.taskId != '') {
        //     this.isEdit = true
        //     this.getTaskInfo()
        // }
        // const isView = this.$route.query && this.$route.query.isView
        // if (isView && isView == 'true') {
        //     this.isView = true
        // } else {
        //     this.isView = false
        // }
        // const isCheck = this.$route.query && this.$route.query.isCheck
        // if (isCheck && isCheck == 'true') {
        //     this.isCheck = true
        // } else {
        //     this.isCheck = false
        // }

        this.taskId = this.partsTaskId
    },
    mounted() {
        this.getUserList()
        this.supplierInfoList()
        this.getAccessoryTree()

        if (this.isView) {
            this.getTaskInfo()
        }
    },
    methods: {
        /** 查询用户列表--采购员 */
        getUserList() {
            getUserByRoleList({ roleId: '104' }).then((response) => {
                this.userList = response.data
            })
        },
        /** 厂家 */
        supplierInfoList() {
            supplierInfoList().then((response) => {
                this.supplierList = response.rows
            })
        },
        /** 配件类型 */
        getAccessoryTree() {
            getAccessoryTree().then((response) => {
                this.equipmentTypeList = response.data
                this.equipmentTypeList.forEach((item, index) => {
                    if (item.children.length > 0) {
                        item.children.forEach((item2, index2) => {
                            if (item2.children.length > 0) {
                                item2.children.forEach((item3) => {
                                    item3.machineTypeName = item2.label
                                    item3.specificationType = item3.label
                                    item3.partId = item3.id
                                    // item3.purchasePrice = 1
                                    // item3.purchaseNum = 1
                                    this.$set(item3, 'purchasePrice', 0)
                                    this.$set(item3, 'purchaseNum', 1)
                                })
                            }
                        })
                    }
                })
            })
        },
        //添加机具类型
        select(row) {
            console.log(row)
            if (row.level == 3) {
                for (let i = 0; i < this.equipmentList.length; i++) {
                    if (this.equipmentList[i].id == row.id) {
                        this.equipmentList.splice(i, 1)
                        break
                    }
                }
                this.$set(row, 'supplierId', '')
                this.$set(row, 'purchasePrice', 0)
                this.$set(row, 'purchaseNum', 1)
                this.equipmentList.unshift(row)
            }
        },
        //选择机具厂家
        changeSupplier(supplierId) {
            this.equipmentList.forEach((item) => {
                this.$set(item, 'supplierId', supplierId)
            })
        },
        /** 新增按钮操作 */
        handleSave() {
            if (this.equipmentList.length > 0) {
                this.$refs['maForm'].validate((valid) => {
                    if (valid) {
                        console.log(this.maForm, 'maForm')
                        console.log(this.equipmentList, 'equipmentList')
                        let isEmpty = true
                        this.equipmentList.forEach((item) => {
                            if (item.purchaseNum == '' || !item.purchaseNum) {
                                isEmpty = false
                            }
                        })
                        console.log(this.taskId)

                        this.maForm.taskId = this.taskId
                        this.maForm.partDetailsList = this.equipmentList
                        console.log(this.maForm)
                        if (isEmpty) {
                            if (this.equipmentList.length > 0) {
                                this.$modal
                                    .confirm('是否确认保存当前页面')
                                    .then(function () {})
                                    .then(() => {
                                        if (this.isEdit) {
                                            console.log('编辑')
                                            this.loading = true
                                            updatePurchaseAccessory(
                                                this.maForm,
                                            ).then((response) => {
                                                if (response.code == 200) {
                                                    this.$modal.msgSuccess(
                                                        '编辑成功',
                                                    )
                                                    // this.$tab.closeOpenPage({
                                                    //     path: '/store/newBuy/newAccessoryList',
                                                    // })

                                                    this.$emit(
                                                        'partsSaveSuccess',
                                                    )
                                                }
                                                this.loading = false
                                            })
                                        } else if (!this.isEdit) {
                                            console.log('新增')
                                            this.loading = true
                                            addPurchaseAccessory(
                                                this.maForm,
                                            ).then((response) => {
                                                if (response.code == 200) {
                                                    this.$modal.msgSuccess(
                                                        '新增成功',
                                                    )
                                                    // this.$tab.closeOpenPage({
                                                    //     path: '/store/newBuy/newAccessoryList',
                                                    // })
                                                    this.$emit(
                                                        'partsSaveSuccess',
                                                    )
                                                }
                                                this.loading = false
                                            })
                                        }
                                    })
                                    .catch(() => {})
                            } else {
                                this.$modal.msgError(
                                    '请先选择并添加机具类型！！！',
                                )
                            }
                        } else {
                            this.$modal.msgError('请填写采购数量！！！')
                        }
                    }
                })
            } else {
                this.$modal.msgError('请先添加机具类型')
            }
        },
        // 返回列表页
        jumpList() {
            const obj = { path: '/store/newBuy/newAccessoryList' }
            this.$tab.closeOpenPage(obj)
        },
        //获取任务详情--- 编辑回显数据
        getTaskInfo() {
            // this.loading = true;
            getPurchaseAccessoryDetails({ taskId: this.taskId }).then(
                (response) => {
                    // this.taskInfo = response.data
                    this.maForm.purchaseTime = response.data.purchaseTime
                    this.maForm.arrivalTime = response.data.arrivalTime
                    this.maForm.purchaser = response.data.purchaser
                    this.maForm.remark = response.data.remark
                    this.equipmentList = response.data.partDetailsList
                    // this.loading = false;
                },
            )
        },

        /** 删除按钮操作 */
        handleDelete(row) {
            console.log(row.id)
            this.equipmentList.forEach((item, index) => {
                if (item.id == row.id) {
                    this.equipmentList.splice(index, 1)
                }
            })
        },
        // 取消按钮
        cancel() {
            this.open = false
            this.reset()
        },
        // 表单重置
        reset() {
            if (this.$refs.menu != undefined) {
                this.$refs.menu.setCheckedKeys([])
            }
            ;(this.menuExpand = false),
                (this.menuNodeAll = false),
                (this.deptExpand = true),
                (this.deptNodeAll = false),
                (this.form = {
                    roleId: undefined,
                    roleName: undefined,
                    roleKey: undefined,
                    roleSort: 0,
                    status: '0',
                    menuIds: [],
                    deptIds: [],
                    menuCheckStrictly: true,
                    deptCheckStrictly: true,
                    remark: undefined,
                })
            this.resetForm('form')
        },

        // 多选框选中数据
        handleSelectionChange(selection) {
            this.ids = selection.map((item) => item)
            this.single = selection.length != 1
            this.multiple = !selection.length
        },
        //验收后禁止勾选
        selectable(row, index) {
            if (row.status == 0) {
                return true
            } else {
                return false
            }
        },
        /** 验收按钮操作 */
        handleCheck(row) {
            console.log(row)
            let rowData = row
            rowData.checkNum = rowData.purchaseNum
            rowData.checkResult = rowData.checkResult || '通过'
            this.form = rowData
            this.open = true
            this.title = '验收'
        },
        /** 验收提交按钮 */
        submitForm: function () {
            console.log(this.form)
            let equipments = [this.form]
            console.log(equipments)
            this.$refs['form'].validate((valid) => {
                if (valid) {
                    checkPurchaseAccessory(equipments).then((response) => {
                        if (response.code == 200) {
                            this.$message({
                                message: '验收成功',
                                type: 'success',
                            })
                            this.open = false
                            this.getTaskInfo()
                        }
                    })
                }
            })
        },
        /** 批量验收按钮操作 */
        handleListCheck() {
            // console.log(this.ids)

            this.aform = {
                checkResult: '通过',
                checkUrl: '',
                checkUrlName: '',
            }
            this.imageUrl = ''
            this.openAll = true
            this.title = '批量验收'
        },
        submitListForm: function () {
            console.log(this.aform)
            this.ids.forEach((item) => {
                item.checkNum = item.purchaseNum
                item.checkResult = this.aform.checkResult
            })
            console.log(this.ids)
            let equipments = this.ids
            console.log(equipments)
            this.$refs['aform'].validate((valid) => {
                if (valid) {
                    checkPurchaseAccessory(equipments).then((response) => {
                        if (response.code == 200) {
                            this.$message({
                                message: '验收成功',
                                type: 'success',
                            })
                            this.openAll = false
                            this.getTaskInfo()
                        }
                    })
                }
            })
        },

        /** 导出按钮操作 */
        handleExport() {
            // this.download('material/purchaseAccessory/export', {
            //   ...this.addForm
            // }, `role_${new Date().getTime()}.xlsx`)
        },
    },
}
</script>
