<template>
    <div>
        <crud-template v-if="itemStart" class="as-weight" :ref="(el) => crudRef = el" :home-data="field"
            @btnSearch="btnSearch" @refreshLeft="refreshLeft" :initData="initItem" :tableData="tableData"
            @handleEdit="handleEdit" @cancel="cancel" @importData="importData" @CurrentChange="handleCurrentChange">
            <template #search>
              <el-form
                  :model="searchForm"
                  :rules="rules"
                  :ref="(el) => (searchFormRef = el)"
                  v-loading="formLoding"
              >
                <el-form-item
                  label="签号:"
                  prop="obuId"
              >
                <el-input
                    maxlength="60"
                    v-trim
                    clearable
                    v-model="searchForm.obuId"
                    style="width: 200px"
                    placeholder="请输入签号"
                />
              </el-form-item>
              </el-form>
                <el-input maxlength="60" v-trim clearable v-model="searchForm.vehiclePlate" placeholder="请输入车牌号"
                    style="width: 320px;">
                    <template #append>
                        <el-select clearable v-model="searchForm.vehiclePlateColor" placeholder="请选择车牌颜色"
                            style="width: 150px">
                            <el-option :label="item.label" :key="item.label" :value="item.value"
                                v-for="item in VEHICLE_COLOR_TYPE" />
                        </el-select>
                    </template>
                </el-input>
            </template>
            <template #tableOperation>
                <el-button type="primary" v-if="IsPermission(route, 'LOWER_BLACK')" @click="addBlack">下黑</el-button>
            </template>
            <template #dialog>
                <el-form label-position="right" label-width="110px" :model="addForm" :rules="rules"
                    :ref="(el) => dataFormRef = el" v-loading="formLoding">
                    <el-form-item label='签号:' prop="obuId" v-if="typeOption === '下黑'">
                        <el-input maxlength="60" v-trim clearable v-model="addForm.obuId" placeholder="请输入签号"
                            type="text" />
                    </el-form-item>
                    <el-form-item label='黑名单类型:' prop="type" v-if="typeOption === '下黑'">
                        <el-select clearable v-model="addForm.type" style="width: 100%" placeholder="请选择黑名单类型">
                            <el-option v-for="item in typeList" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </el-form-item>
                  <el-form-item label='原因:' prop="reason">
                    <el-input maxlength="200" v-trim clearable v-model="addForm.reason" placeholder="请输入原因"
                              :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" />
                  </el-form-item>
                  <el-form-item label='解决方案:' prop="solution" v-if="typeOption === '下黑'">
                    <el-input maxlength="200" v-trim clearable v-model="addForm.solution" placeholder="请输入解决方案"
                              :autosize="{ minRows: 2, maxRows: 4 }" type="textarea" />
                  </el-form-item>

                </el-form>
            </template>
            <template #operation="{ scope }">
                <el-button type="primary" @click="handleEdit(scope.row, '反白')" size="small"
                    v-if="scope.row.status === 1 && IsPermission(route, 'REVERSE')">反白</el-button>
            </template>
            <template #footer>
                <el-button type="default" @click="cancel">取消</el-button>
                <el-button type="primary" @click="submitHandle()">确定</el-button>
            </template>
        </crud-template>
    </div>
</template>

<!-- 签黑名单管理 -->
<script lang="ts" setup>
    // @ts-ignore crudFrom模板
    import CrudTemplate from '@/crud/index.vue'
    import { ref, onMounted, computed } from 'vue'
    import { ElMessage } from "element-plus";
    import { useDebounce, getDictLabel } from "@/utils/utils";
    import BaseService from "@/utils/baseService";
    import $storeinitData from "@/store/initData"; //引入tab vuex
    import { obuBlacklistApi, obuInversionApi } from "@/api/onlineBusinessHall/afterSales"
    import { useRoute } from 'vue-router';
    import { IsPermission } from "@/router/routerUtil";

    //车牌颜色
    const VEHICLE_COLOR_TYPE = computed(() => {
        return $storeinitData.state.dictData['VEHICLE_COLOR_TYPE'] || []
    })

    const SOURCE_TYPE = computed(() => {
      return $storeinitData.state.dictData['SOURCE_TYPE'] || []
    })

    //或取路由传入过来的对象数据
    const route = useRoute();
    const dataFormRef = ref()
    const searchFormRef = ref()
    const crudRef = ref()
    const itemStart = ref(true)
    const searchForm = ref({
        obuId: "",
        vehiclePlate: '',
        vehiclePlateColor: '',
    })
    const typeOption = ref(""); // 新增下黑或者反白操作
    const initItem = {
        type: "",
        obuId: "",
        status: "",
        reason: "", //反白原因
    }
    const addForm: any = ref({
        ...initItem
    })
    const formLoding = ref(false);
    const rules = {
        reason: [{ required: true, message: "请输入原因", trigger: "blur" }],
      solution: [{ required: true, message: '请输入解决方案', trigger: 'blur' }],
      type: [{ required: true, message: "请选择类型", trigger: "change" }],
        obuId: [{ required: true, message: "请输入签号", trigger: "blur" }],
    }
    const tableData = ref([] as any[]);
    const typeList = computed(() => {
      return $storeinitData.state.dictData['OBU_BLACK_TYPE'] || []
    })
    //表单数据配置
    const field = ref({
        tabSize: 'small', //Table 的尺寸 large / default /small (默认default)
        searchShow: IsPermission(route, 'QUERY_BASE'), //是否显示搜索模块(默认false)
        border: true, //是否添加边框(默认false)
        dialogCustom: true, //自定义Dialog (默认false)
        dialogFooter: true, //隐藏弹窗页脚显示 (默认false)
        dialogWidth: '40%', //dialog宽度 (默认40%)
        crudShow: true, //是否显示CURD操作栏 (默认true)
        crudChildShow: true, //是否显示CURD子操作栏 (默认true)
        paginStart: true, //是否显示分页查询 (默认false)
        titleDialog: "", //table 标题
        tableOperation: true,
        paging: {
            pageSize: 10,
            currentPage: 1,
            total: 0
        },
        crud: {
            add: false,
            edit: false,
            delete: false,
            derive: false,
            search: false,
            refresh: false,
        },
        searchOperation: {
            isDownload: false,
            isAdd: false,
            isTransferMachine: false,
            isToLead: true, // 导入
            isTemplate: true,
            templateUrl:
                import.meta.env.VITE_APP_UPLOAD_URL +
                'zhywpt-issuer/template/managew/签批量下黑反白模板.xlsx',
            templateFileName: '签批量下黑反白模板',
        },
        tableSize: -1,
        operateShow: true, //是否为表格添加操作栏(默认true)
        operateTitle: '操作', //操作栏标题(默认为"")
        operateFixed: true, //操作栏是否固定(默认false)
        operateWidth: '150', //操作栏宽度
        operate: {
            info: true,
            edit: false, //是否编辑(默认true)
            delete: false, //是否删除(默认true)
            announcement: false, // 公告
            remark: false, // 详情
            forbidden: false, // 禁用
            enable: false, // 启用
            authorization: false, // 授权
            cancel: false,// 取消订单
            writeOff: false,// 注销
            make: false,// 补缴
        },
        extend: [
            {
                label: '序号',
                type: 'index', //类型:selection,index,expand
                width: '', //表头宽度
            },
        ],
        field: [
            {
                prop: 'obuId',
                label: '签号',
                width: 170,
                form: {
                    width: '45%',
                    type: 'input',
                }
            },
            {
                prop: 'agencyId',
                label: '渠道编号',
                width: 170,
                form: {
                    width: '45%',
                    type: 'input',
                }
            },
            {
                prop: 'type',
                label: '类型',
                funRuleStarts: true,
                funRule: (val: any) => {
                    return getDictLabel(typeList, val)
                },
                form: {
                    width: '45%',
                    type: 'select',
                    listData: typeList
                }
            },
            {
                prop: 'status',
                label: '状态',
                funRuleStarts: true,
                width: 120,
                funRule: (val: any) => {
                    //1-在黑，2-已反白
                    if (val == 1) {
                        return '在黑'
                    } else if (val == 2) {
                        return '已反白'
                    }
                    return val
                },
                form: {
                    width: '45%',
                    type: 'input',
                    funRuleStarts: true,
                    funRule: (val: any) => {
                        //1-在黑，2-已反白
                        if (val == 1) {
                            return '在黑'
                        } else if (val == 2) {
                            return '已反白'
                        }
                        return val
                    },
                }
            },
            {
                prop: 'vehiclePlate',
                label: '车牌号',
                width: 170,
                form: {
                    width: '45%',
                    type: 'input',
                }
            },
            {
                prop: 'vehiclePlateColor',
                label: '车牌颜色',
                width: 170,
                listData: VEHICLE_COLOR_TYPE,
                form: {
                    width: '45%',
                    type: 'select',
                    listData: VEHICLE_COLOR_TYPE
                }
            },
            {
                prop: 'createTime',
                label: '下黑时间',
                width: '170px',
                funRuleStarts: true,
                funRule: (val: any) => {
                    if (val) {
                        return val.replaceAll('T', ' ')
                    }
                    return val
                },
                form: {
                    width: '45%',
                    type: 'input',
                    funRuleStarts: true,
                    funRule: (val: any) => {
                        if (val) {
                            return val.replaceAll('T', ' ')
                        }
                        return val
                    },
                }
            },
            {
                prop: 'reasonIn',
                label: '下黑原因',
                form: {
                    width: '45%',
                    type: 'input',
                }
            },
            {
                prop: 'staffIdIn',
                label: '下黑操作工号',
                width: 120,
                hide: true,
                form: {
                    width: '45%',
                    type: 'input',
                }
            },
            {
              label: '下黑来源',
              prop: 'sourceIn',
              listData: SOURCE_TYPE,
              hide: true,
              form: {
                width: '45%',
                type: 'select',
                listData: SOURCE_TYPE,
              },
            },
            {
                prop: 'releaseTime',
                label: '反白时间',
                width: '170px',
                funRuleStarts: true,
                funRule: (val: any) => {
                    if (val) {
                        return val.replaceAll('T', ' ')
                    }
                    return val
                },
                form: {
                    width: '45%',
                    type: 'input',
                    funRuleStarts: true,
                    funRule: (val: any) => {
                        if (val) {
                            return val.replaceAll('T', ' ')
                        }
                        return val
                    },
                }
            },
            {
                prop: 'reasonOut',
                label: '反白原因',
                form: {
                    width: '45%',
                    type: 'input',
                }
            },
            {
                prop: 'staffIdOut',
                label: '反白操作工号',
                width: 170,
                hide: true,
                form: {
                    width: '45%',
                    type: 'input',
                }
            },
            {
              label: '反白来源',
              prop: 'sourceOut',
              listData: SOURCE_TYPE,
              hide: true,
              form: {
                width: '45%',
                type: 'select',
                listData: SOURCE_TYPE,
              },
            },
        ],
    })
    // 搜索按钮
    function btnSearch() {
      searchFormRef.value.validate((valid: boolean) => {
        if (!valid) {
          return false
        }
        field.value.paging.currentPage = 1;
        getList();
      });
    }
    // 搜索重置
    function refreshLeft() {
        searchForm.value = {
            obuId: "",
            vehiclePlate: '',
            vehiclePlateColor: '',
        }
        field.value.paging.currentPage = 1;
        //因为必须传obuId，所在列表置空，不请求
        //getList();
        tableData.value = [];
    }

    //反白
    function handleEdit(row: any, text) {
        addForm.value.type = row.type;
        addForm.value.obuId = row.obuId;
        addForm.value.status = 2; // 2是反白
        crudRef.value.dialogFormVisible = true;
        crudRef.value.title = text;
        typeOption.value = text
        console.log("====", addForm.value)
    }
    // 取消
    function cancel() {
        addForm.value = {
            ...initItem
        }//清空数据
        crudRef.value.reset();
        crudRef.value.dialogFormVisible = false;
        crudRef.value.title = "";
        typeOption.value = ""
    }
    function handleCurrentChange(val: number) {
        field.value.paging.currentPage = val;
        getList();
    }
    // 提交
    function submitClick() {
        dataFormRef.value.validate((valid: boolean) => {
            if (!valid) {
                return false;
            }
            let api = '/managew/api/bls/obu/obuIn';
            let params = {
                ...addForm.value
            }
          if(params.status == 2){
            api = '/managew/api/bls/obu/obuOut'
          }
            BaseService.post(api, params).then((res: any) => {
                if (res && res.statusCode === 0) {
                    let bizContent = res.data
                    console.log(bizContent, 'bizContentbizContentbizContent')
                    if (bizContent.uploadStatus == 1) {
                        let msg = '操作成功';
                        //兼容后端把一些报错返回在info里面
                        if (bizContent.info && !bizContent.info.info) {
                            msg = bizContent.info
                        }
                        ElMessage.success(msg);
                        //因为需求查询列表必须传obuId，所以为了方便用户查看最新操作的数据，更新查询框的obuId
                        searchForm.value.obuId = addForm.value.obuId
                        getList();
                        cancel();
                    } else {
                        ElMessage.error(bizContent.message)
                    }
                } else {
                    ElMessage.error(res.message)
                }
            })
        });
    }
    const submitHandle = useDebounce(submitClick)
    function getList() {
        crudRef.value.tableLoding = true;
        let params: any = {
            methods: "page",
            pageNo: field.value.paging.currentPage,
            pageSize: field.value.paging.pageSize,
        }
        let searchFormList = { ...searchForm.value }
        for (let key in searchFormList) {
            if (searchFormList[key]) {
                params[key] = searchFormList[key]
            }
        }
        BaseService.post('/managew/api/bls/obu/query', params).then((res: any) => {
            if (res && res.statusCode === 0) {
                let bizContent = res.data
                let data = bizContent.results || [];
                console.log("===bizContentData", data)
                tableData.value = data;
                crudRef.value.tableLoding = false;
                field.value.paging.total = bizContent.totalCount;
            } else {
                crudRef.value.tableLoding = false;
                ElMessage.error(res.message)
            }
        })
        crudRef.value.tableLoding = false;
        tableData.value = [
            {
                id: 1
            }
        ]
    }
    function importData(url) {
      BaseService.postN('/managew/api/bls/obu/obuImport', { excelUrl: url }).then((res: any) => {
        if (res && res.code === 0) {
          console.log(res)
          const errUrl = res.data?.excelUrl ?? ''
          if (errUrl) {
            ElMessage.error("导入失败，请查看下载到本地文件的具体错误信息");
            BaseService.getDownload(
                import.meta.env.VITE_APP_UPLOAD_URL + errUrl,
                '错误信息文件'
            )
          } else {
            ElMessage.success("导入成功");
          }
        }
      });
    }
    // 新增下黑
    function addBlack() {
        addForm.value.status = 1; //下黑
        crudRef.value.dialogFormVisible = true;
        crudRef.value.title = "下黑";
        typeOption.value = "下黑";
    }
    onMounted(() => {
        //getList();
    })

</script>
<style scoped></style>